ajax get checkbox name which is an array - javascript

updated
I'm using while loop to display checkbox, the value of the checkbox is the amount. The codes can now display the total value when a checkbox is checked through the ajax function. During form submit, how do i obtain the $ID of checked value? As the name of the checkbox is not an array, i have no idea how to do that other way. Please help :'( Thanks in advance!
PHP:
<table>
<form name="listForm">
<?php
while($row=mysql_fetch_assoc($result)){
$ID = $row['ID'];
$amount = $row['amount'];
?>
<tr>
<td><input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" value="<?php echo $amount;?>" onclick="calculate();"></td>
</tr>
<?php
}?>
</table>
</form>
javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}

You need to get the "data-payment-id" attribute from the checkboxes that are clicked as well. I'd store them in an array, then json stringify it to be sent in your form.
Javascript:
function calculate(){
document.listForm.payID.value = '';
var sum = 0;
var count = 0;
var idList = [];
for (i=0;i< document.listForm.payID.length ; i++) {
if (document.listForm.payID[i].checked) {
sum = sum + parseInt(document.listForm.payID[i].value);
count = count + 1;
idList.push(document.listForm.payID[i].getAttribute('data-payment-id'));
}
}
document.getElementById('sum').value = sum;
document.getElementById('count').value = count;
document.getElementById('idList').value = JSON.stringify(idList);
return true;
}
And then for your form, update it to have the hidden inputs and the onsubmit function - here's what I was using for a test:
HTML Form:
<form name="listForm" action="aoeu.php" method="post" onsubmit="calculate()">
<input type='checkbox' name="payID" value='1' data-payment-id='aaa'> 1<br>
<input type='checkbox' name="payID" value='2' data-payment-id='bbb'> 2<br>
<input type='checkbox' name="payID" value='3' data-payment-id='ccc'> 3<br>
<input type='hidden' id='sum' name='sum'>
<input type='hidden' id='count' name='count'>
<input type='hidden' id='idList' name='idList'>
<button type='submit'>Submit</button>
</form>
Then just make sure to json_decode() the idList you get in your PHP post.

I have updated now. In your php code amend this line:
<input type="checkbox" name="payID" data-payment-id="<?php echo $ID;?>" id="payment_id[]" onClick="calculate()" value="<?php echo $amount;?>" >
And your Javascript function:
function calculate(){
var sum = 0;
var count = 0;
var a1=document.listForm['payment_id[]'];
for(i=0;i<a1.length;i++){
if (a1[i].checked){
sum += parseInt(a1[i].value);
count = count + 1;
}
}
document.getElementById('payable').innerHTML = "Total record chosen= "+ count +"<br>Total amount= " + sum + "<br>";
}

Related

Javascript - perform operation vertically and horizontally with dynamic text input

need help i am working with some text inputs here that are dynamic depending on how many the user enter. what i wanted to do is to compute the text inputs automatically after user input value using onkeyup javascript.
here the php and html code:
<?Php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply()' id='tb1'>";
echo "x";
echo "<input type='text' onkeyup='multiply()' id='tb2'>";
echo "=";
echo "<input type='text' onkeyup='multiply()' id='tb3'>";
echo "<br>";
}
?>
total:<input type='text' onkeyup='multiply()' id='tb4'>
and here's the javascript:
<script>
function multiply(){
var textbox1 = document.getElementById('tb1').value;
var textbox2 = document.getElementById('tb2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb3').value = result;
}
}
</script>
now, the first row of text inputs works fine but the remaining text inputs doesn't I know i'm missing something here and i can't figure it out, how can
i compute horizontally those values from tb1 and tb2 then display it on tb3
and compute vertically all the values of tb3 and display it in tb4. any help is much appreciated.TIA
Well all rows contain elements with same ids. So row 1 will contain elements with ids: tb1, tb2, tb3. Row 2 will also contain elements with ids tb1, tb2 and tb3.
The id of each element on a page needs to be unique. You can make the ids unique by appending the row number to the id. For example:
<?php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-1'>";
echo "x";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-2'>";
echo "=";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-3'>";
echo "<br>";
}
?>
Total: <input type='text' id='tb4'> <input type='button' onclick='CalculateSum()' title='Calculate Sum'>
Your JavaScript code will then look as follows:
<script>
function multiply(row) {
var textbox1 = document.getElementById('tb' + row + '-1').value;
var textbox2 = document.getElementById('tb' + row + '-2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb' + row + '-3').value = result;
}
}
function CalculateSum() {
let total = 0;
for (let i=0; i < 10; i++) {
total += document.getElementById('tb' + i + '-3').value;
}
document.getElementById('tb4').value = total;
}
</script>

Getting id from append table and use it in arithmetic javascript

I'm trying to get the id from append table and use it in arithmetic.
Here's the modal where i append the table and its in php
<tbody>
<tr class="item-row" id="item-row" onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' id='productUse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='productMsrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;' id='cost'><textarea rows='4' cols='10' name='Dealerphp' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td</td></tr>";
}
?>
</tbody>
here's the append javascript.
<script type="text/javascript">
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea class="productid" id="prc" value="'+ value +'</textarea></td><td class="item-name"><textarea class="productuse" id="productuse" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea class="description" id="description" value= "' + value2 +' </textarea></td><td class="item-name"><textarea class="msrp" id="msrp" value= "' + value3 + ' </textarea> </td><td class="item-name"><textarea class="cost" name="cost" id="'+ value4 + ' </textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty"></textarea></td><td class="item-name"><textarea id="price" class="price" name="price" disabled></textarea></td></tr>');
console.log(value4);
}));
});
});
</script>
and here's the arithmetic javascript to get the id, multiply to the column of qty and get the total.
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("₱" ,"") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
got it
function update_price() {
var row = $(this).parents('tr');
var a , w = 0;
var a = row.find('.cost').val().replace(/\,/g,'');
var w = row.find('.qty').val().replace(/\,/g,'');
var price = Number(a) * Number(w);
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}

PHP posting array values generated in JS for loop

I am using this script to generate a code which will later appear in a form.
I have this code working on 2 pages, but I have no idea why it is not able to post to te next page.
Below is my code:
function add(){
var coun = document.getElementById('count').value;
if(coun==""){var count = 1;}
else{var count = (coun*1)+1;}
if(count>=1){
show('cont_del');
}
var field = "";
var table = "";
var desc_arr = "";
var itn_arr = "";
var qty_arr = "";
var cls_arr = "";
var unp_arr = "";
var tot_arr = "";
for(var f=1;f<count;f++){
desc_arr = document.getElementById('desc'+f).value;
itn_arr = document.getElementById('itn'+f).value;
qty_arr = document.getElementById('qty'+f).value;
<? if($_POST['type']=="o"){ ?>
cls_arr = document.getElementById('cls'+f).value;
<? } ?>
unp_arr = document.getElementById('unp'+f).value;
tot_arr = document.getElementById('tot'+f).value;
field = field+"<table class='style5'><tr bgcolor='#FFFFFF'>";
field = field+"<td width='70'><b>"+f+"</b></td>\n";
<? if($_POST['type']!="s"){ ?>
field = field+"<td width='130'>";
field = field+"<input name='itn[]' id='itn"+f+"' type='text' class='input' size='5' maxlength='11' value='"+itn_arr+"'>";
field = field+"</td>\n";
<? } ?>
field = field+"<td width='200'>";
field = field+"<input name='desc[]' id='desc"+f+"' type='text'
class='input' size='30' value='"+desc_arr+"'>";
field = field+"</td>\n";
field = field+"<td width='70'>";
field = field+"<input name='qty[]' id='qty"+f+"'
onchange='totcalc("+f+");' type='text' class='input' size='3'
value='"+qty_arr+"'>";
field = field+"</td>\n";
<? if($_POST['type']=="o"){ ?>
field = field+"<td width='70'>";
field = field+"<input name='cls[]' id='cls"+f+"' type='text'
class='input' size='3' value='"+cls_arr+"'>";
field = field+"</td>\n";
<? } ?>
field = field+"<td width='150'>";
field = field+"<input name='unp[]' id='unp"+f+"'
onchange='totcalc("+f+");digit("+f+")' type='text' class='input'
size='10' value='"+unp_arr+"'>";
field = field+"</td>\n";
field = field+"<td width='150'>";
field = field+"<input name='tot[]' id='tot"+f+"' type='text'
class='input' size='10' value='"+tot_arr+"'>";
field = field+"</td>\n";
field = field+"</tr></table>\n\n";
}
var table = "<table class='style5'><tr bgcolor='#FFFFFF'>";
table = table+"<td width='70'><b>"+count+"</b></td>\n";
<? if($_POST['type']!="s"){ ?>
table = table+"<td width='130'>";
table = table+"<input name='itn[]' id='itn"+count+"' type='text'
class='input' size='5' maxlength='11'>";
table = table+"</td>\n";
<? } ?>
table = table+"<td width='200'>";
table = table+"<input name='desc[]' id='desc"+count+"' type='text'
class='input' size='30'>";
table = table+"</td>\n";
table = table+"<td width='70'>";
table = table+"<input name='qty[]' id='qty"+count+"'
onchange='totcalc("+count+");' type='text' class='input' size='3'
value='0'>";
table = table+"</td>\n";
<? if($_POST['type']=="o"){ ?>
table = table+"<td width='70'>";
table = table+"<input name='cls[]' id='cls"+count+"' type='text'
class='input' size='3'";
table = table+"</td>\n";
<? } ?>
table = table+"<td width='150'>";
table = table+"<input name='unp[]' id='unp"+count+"'
onchange='totcalc("+count+"); digit("+count+")' type='text'
class='input' size='10' value='0.00'>";
table = table+"</td>\n";
table = table+"<td width='150'>";
table = table+"<input name='tot[]' id='tot"+count+"'
type='text' class='input' size='10' value='0.00'>";
table = table+"</td>\n";
table = table+"</tr></table>\n\n";
document.getElementById("add").innerHTML = field + table;
document.getElementById("count").value = (count*1);
}
Later everything will be posted to the a div id='add' container in a nested table.
When I post the form there are no variables posted.

Codeigniter and javascript-add dynamic input and radio fields

hi guys I am pretty newbish in javascript and php for that matter. I am making a page where user will choose either to create a radio or input fields for others to solve.
Everything works fine except, when I save the form, fields are not in the order I added them because I first loop over the 'input' fields and then over the 'radio' fields. I know this is probably not the way to do it, feel free to give me an alternative.
Any help would be appreciated, thanks in advance.
VIEW
<h1>Add questions</h1>
<form action="" method="post">
<div id='pit'>
<span id="add_input"><a href="#" class='button' style='font-size:1.5em;'><span>» add input </span></a></span><br>
<span id="add_radio"><a href="#" class='button'style='font-size:1.5em;'><span>» Dodaj yes/no question</span></a></span>
</div>
<input type="hidden" name="id" value="<?= $this->uri->segment(3); ?>" />
<input id="go" class="button" name="submit" type="submit" value="Save" />
</form>
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /></p>' );
a=count;
document.write(a);
});
});</script>
<script type="text/javascript">
var count = 0;
$(function(){
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input id="radio_' + count + '" name="radios[]' + '" type="text" /></p>' );
});
});</script>
CONTROLLER
$id=$this->input->post('id');
if($_POST['fields']){
foreach ( $_POST['fields'] as $key=>$value ) {
$tip='input';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
if($_POST['radios']){
foreach ( $_POST['radios'] as $key=>$value ) {
$tip='radio';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
Something like this might work.
Maintain the same count variable in the JavaScript to keep track of which input is created.
Instead of using name="fields[]", use name="field_' + count + '" so you can iterate with a loop in the controller.
VIEW
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input name="field_' + count + '" type="text" /></p>' );
a=count;
document.write(a);
});
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input name="radio_' + count + '" type="text" /></p>' );
});
});
</script>
CONTROLLER
Use a regular expression to extract the necessary values.
$inputs = array();
$id=$this->input->post('id');
foreach($_POST as $key => $value) {
$matches = array();
if (preg_match('/(field|radio)_([\d]+)', $key, $matches)) {
$tip = $matches[1];
$count = $matches[2];
$inputs[$count] = array($id, $value, $tip);
}
}
Loop through the new $inputs array to call your add_questions method.
ksort($inputs);
foreach($inputs as $array) {
$id = $array[0];
$value = $array[1];
$tip = $array[2];
$this->page_model->add_questions($id,$value,$tip);
}

How get the textbox values in array.....to store in database

this is my code...
How get the textbox array value to store in database...
<html>
<head>
<script type="text/javascript">
var max = 4; //highest number to go to
var currentIndex = 0;
function btnClick() {
if(currentIndex < max){
currentIndex++;
postClick();
}
}
function Previous(){
if(currentIndex>0){
currentIndex--;
postClick();
}
}
function postClick() {//whatever you want to happen goes here
var sahans = new Array();
sahans[currentIndex] == d;
var d = document.getElementById("div");
d.innerHTML = "<p><input type='text' name='name"+currentIndex+"[]'>";
d.innerHTML += "<p><input type='text' name='topic"+currentIndex+"[]'>";
document.getElementById("div").style.display = "";
}
</script>
</head>
<body>
<form id="form1">
<div>
<input type="button" value="Previous" onclick="Previous();" />
<input type="button" value="Next" onclick="btnClick();" />
<div id="div"></div>
</div>
</form>
</body>
</html>
JavaScript:
function store(form) {
var input = form.getElementsByTagName('input');
var myarray = Array();
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text') {
myarray[input[i].getAttribute('name')] = input[i].value;
}
}
for (var i in myarray) {
alert(i + ': ' + myarray[i]);
}
}
HTML:
<form onsubmit="store(this); return false">
<p>
<input type="text" name="name" /><br />
<input type="text" name="topic" />
</p>
<p>
<input type="submit" value="Store in database" />
</p>
</form>
Edit:
Ok, now I made a full example with AJAX and the actual saving to the database. The AJAX call uses 'POST'. Simply fill in the number of fields that you want in the max variable.
JavaScript:
var max = 10;
var current = 0;
function goto(form, pos) {
current += pos;
form.prev.disabled = current <= 0;
form.next.disabled = current >= max - 1;
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
function store(form) {
var input = form.getElementsByTagName('input');
var data = '';
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text')
data += '&' + input[i].getAttribute('name') + '=' + input[i].value;
}
data = encodeURI('n=' + max + data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('POST', 'store.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.setRequestHeader('Connection', 'close');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != '')
alert(this.responseText);
else {
form.submit.value = 'Saved!';
setTimeout(function() { form.submit.value = 'Save to database' }, 500);
}
}
}
xhr.send(data);
}
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('div')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset><legend>Entry ' + (i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
HTML:
<form action="submit.php" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<div>
<noscript>Please enable JavaScript to see this form correctly.</noscript>
</div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
Users who have JS disabled will see what's in the <noscript> tag, otherwise it's replaced with the fieldsets. Also it's good to make an alternative submit page (submit.php) for users who have JS disabled. Below is store.php, the AJAX submit script.
PHP (store.php):
<?php
if (empty($_POST['n']) || $_POST['n'] < 1) die('Invalid request!');
$fields = array('name', 'topic');
$errors = '';
for ($i = 0; $i < $_POST['n']; $i++) {
foreach ($fields as $field) {
if (empty($_POST[$field . $i]))
$errors .= '- ' . $field . ' ' . ($i + 1) . "\n";
}
}
if ($errors != '')
die("Please fill in the following fields:\n" . $errors);
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb', $db);
for ($i = 0; $i < $_POST['n']; $i++) {
$name = mysql_real_escape_string($_POST['name' . $i]);
$topic = mysql_real_escape_string($_POST['topic' . $i]);
mysql_query(' INSERT INTO entries (id, name, topic) VALUES (' . $i . ', "' . $name . '", "' . $topic . '")
ON DUPLICATE KEY UPDATE name = "' . $name . '", topic = "' . $topic . '"
') or die('Database error!');
}
mysql_close($db);
?>
The output text of this script (if there is an error) is displayed in the JavaScript alert.
I hope it's working for you now.
This would be help ful for you
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<script type="text/javascript">
function validateText(event){
var tar_ele = $(event.target);
if(tar_ele.val() is not valid)
tar_ele.focus();
}
</script>
<input type="text" name="Tue[]" onblur="validateText(event)"/>
javascript text box array and get values and focus on particular field

Categories

Resources