I'm trying to create a simple form which calculates the values in every input field which has subtotal at the start of the name attribute:
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript">
$(function(){
var qty = 0;
var price = 0;
var subtotal = 0;
var qty_r = [];
var price_r = [];
var subs_r = [];
var total = 0;
$('input[name^=qty]').each(function(index) {
qty_r[index] = $(this).val();
});
$('input[name^=price]').each(function(index){
price_r[index] = $(this).val();
});
var j = 0;
for(j = 0; j<=2; j++){
subs_r[j] = parseInt(price_r[j]) * parseInt(qty_r[j]);
}
$('input[name^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
$('input[name^=qty]').keyup(function(){
var basis = $(this).attr("id");
var numbasis = basis.toString();
qty = $(this).val();
price = $('input[name=' + numbasis + ']').val();
subtotal = parseInt(qty) * parseInt(price);
$("#subtotal" + numbasis).val(subtotal);
This is the part where I'm having trouble:
$("input[name=subs]").each(function(index){
total = parseInt($(this).val()) + total;
$('#total').val(total);
});
});
});
</script>
And here's where the data which being calculated comes from:
<?php $products = array(array("prodname"=>"mais", "qty"=>5, "price"=>15), array("prodname"=>"strawberry", "qty"=>7, "price"=>25), array("prodname"=>"kambing", "qty"=>14, "price"=>3)); ?>
<table border="1">
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php foreach($products as $key=>$prods){
?>
<tr>
<td><input type="text" name="prodname<?php echo $key; ?>" value="<?php echo $prods['prodname']; ?>"/></td>
<td><input type="text" id="<?php echo $key; ?>" name="qty<?php echo $key; ?>" value="<?php echo $prods['qty']; ?>"/></td>
<td><input type="text" name="<?php echo $key; ?>" id="price<?php echo $key; ?>" value="<?php echo $prods['price']; ?>"/></td>
<td><input type="text" name="subs" id="subtotal<?php echo $key; ?>" /></td>
</tr>
<?php } ?>
</table>
Total: <input type="text" id="total"/><br/>
The problem is that I'm always getting NaN as a result.
If you're getting NaN you're probably trying to parseInt something that has a return value of NaN. You can do
$("input[name=subs]").each(function(index) {
total = (parseInt($(this).val(), 10) || 0) + total;
$('#total').val(total);
});
Wich will always only add numbers to total.
Let's make that a possible answer, try using:
total = parseInt($(this).val()) + parseInt(total);
Also make sure $(this).val() has a proper value everywhere. If it's blank you will get NaN as a result. For almost any other you will get the right result: http://www.w3schools.com/jsref/jsref_parseInt.asp
It looks like you might be using the wrong selector to set the subtotal values you're using to do the final calculation. Shouldn't it be this:
$('input[id^=subtotal]').each(function(index){
$(this).val(subs_r[index]);
});
Related
I have a table in which there is a row. The first cell of the row contains a drop-down list, and other rows are generated dynamically in case of an argument. The drop-down list contains an option with two fields from the database, one of which is text and the other is a number. The two are linked to each other. The problem that I am stuck with is that in the table The text and its associated number from the database appear only in the first row in the table, I want to repeat this in the table in the rest of the dynamically generated rows, that each text and its associated value appear in the drop down list
The problem in the image
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
$('.select_acount').on('change', function() {
$(this).closest('tr').find('.mount').val($(this).val());
});
var data = <?php echo json_encode($data); ?>;
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount"required></td><td class="td2"><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash" ></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
I have a table that contains a row with the ability to generate other dynamic rows. The drop-down list works now in every new row that is created. I have the first row. The drop-down list that carries data from the database works well and the data is shown in it well, but when adding a new dynamic row and when Clicking on the drop down list the values written on it all show with the word Undefined all the values of the drop down list written on it show up with the word : Undefined I am really stuck any suggestions would be appreciated and thanks
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
for (i=0; i < arr.length; i++)
{
var ItemId = arr[i];
var ItemQuantity = OrderedItemNameQuantityPair[ShopIdNamePair[SelectedShopIndex]+"_"+GetShopItems[ItemId]] ;
<?php
if(isset($_SESSION["ItemIdQuantity"]))
{
$ItemIdQuantity= $_POST['ItemId'];
}
else
{
$ItemIdQuantity = 0;
}
?>
ItemtableData=ItemtableData+'<table class="id_td_ItemContent"><tr><td width="40%" class="OrderedItem">'+GetShopItems[ItemId]+'</td>'+'<td width="10%">'+'<input class="OrderedQuantity" type="text" maxlength="2" name="ItemId" value='+ItemId+'></td>'+'<td width="10%">'+'<input class="OrderedQuantity" type="text" maxlength="2" name="Quantity" value='+"<?php print $ItemIdQuantity; ?>"+'></td>'+'<td width="50%" class="AddToOrder">'+'<input type="Button" onClick="updatedata()">'+'</td></tr></table>';
}
I want to get the input field value ItemId and assing it to $ItemIdQuantity variable.
But the code which i used after page refresh output is not coming.
I want to send variable rows to post2.php with other HTML form variable using POST or GET methods.
The below code gives an error:
Notice: Undefined index: row1 in C:\xampp\htdocs\PhpProject1\OtherUsableItems\post2.php on line 8
post1.php
<html>
<head>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
<script>
function count(tableId){
var rows = document.getElementById(tableId).getElementsByTagName("TR").length;
// window.location.href = "http://localhost/PhpProject1/OtherUsableItem /post2.php?rows=" + rows ;
// alert('Your table has ' + rows + ' rows.');
$.post("post2.php", { 'row' : rows}, function(rows){alert('rows'+rows);});
}
</script>
</head>
<body>
<form action="post2.php" method="post">
<TABLE id="dataTable" border="1">
<TR>
<TD> 1 </TD>
<TD> <INPUT name="n1[]"type="text" /> </TD>
<TD> <INPUT name="n2[]"type="text" /> </TD>
<TD><SELECT name="country[]" type="select-one">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT></TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable');"/>
<button id="bt" onclick="count('dataTable');">Submit</button>
</form>
</body>
</html>
post2.php
<?php
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$country = $_POST['country'];
echo $n1[0];
echo $n2[0];
echo $country[0];
$count = $_POST['row1'];
echo $count;
?>
Try changing to 'row' instead of 'row1'
$n1 = $_POST['n1'];
$n2 = $_POST['n2'];
$country = $_POST['country'];
echo $n1[0];
echo $n2[0];
echo $country[0];
$count = $_POST['row'];
echo $count;
In the future, use print_r to see the value of $_POST.
In addition to the above instructions, I would remove the 2nd <script> tag from post1.php and place the following code into the body at the start of the form:
<form action="post2.php" method="post" >
<input id="rowNumber" type="hidden" name="row" value="1"/>
Also, add the following lines to function addRow:
var rowNumber = document.getElementById('rowNumber');
rowNumber.value = parseInt( rowNumber.value ) + 1;
The problem is that you are not sending the correct Post value.
check if this line :
var rows =
document.getElementById(tableId).getElementsByTagName("TR").length;
it returns values something like: {name:'value',name2:'value2'}
after that you will be able to access via php using $_POST['name']...
and this line :
$.post("post2.php", { 'row' : rows}, function(rows){alert('rows'+rows);});
replaced with:
$.post("post2.php", rows, function(rows){alert('rows'+rows);});
else you will be accessing with $_POST['row']
For some reasons my javascript form validation does not go through every row in the table.
I created the table with the codes below:
The $usr variable is just a result of another process:
<form name="myForm" action="addAccessories.php" method="post" onsubmit="return validateForm(this);">
<table border="1" id="IT">
<tr>
<th>Barcode<em>*</em></th>
<th>Current stock</th>
</tr>
<?php
for($id=1; $id<=$usr; $id++){
?>
<tr>
<td><input type="hidden" name="id[]" value="<?php echo $id; ?>" />
<input type="text" name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>
<td><input type="text" name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
<?php
}
?>
<tr>
<td> </td>
<td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
</tr>
</table>
</form>
The number of rows from this table is: rows = $usr + 1
My validation form codes:
<script type="text/javascript">
function validateForm(){
var errors = [];
for(i = 1; i < document.getElementById("IT").rows.length; i++){
var barcode = document.getElementById('bar_code'+i).value;
var des = document.getElementById('description'+i).value;
var num_stock = document.getElementById('num_stock'+i).value;
if(barcode == null || barcode == ""){
errors[errors.length] = "You must enter barcode.";
}
if(isNaN(num_stock)){
errors[errors.length] = "Current stock must be an integer";
}
if(num_stock < 0){
errors[errors.length] = "Current stock must be a positive number";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
This process only validates the 1st row in the table then stop. Can anyone show me what went wrong and how to fix it?
Thank you very much for your help
Your code is making life way more complex than it needs to be. A simpler approach is to just deal with the form controls, e.g. since you are already passing a reference to the form from the submit listener:
function validateForm(form) {
var errors = [];
var c, cs = form.elements;
var reB = /^bar_code/;
var reN = /^num_stock/;
var reD = /^[0-9]+$/;
for (var i=0, iLen=cs.length; i<iLen; i++) {
c = cs[i];
if (reB.test(c.name) && c.value == '') {
errors.push('You must enter barcode.'];
} else if (reN.test(c.name) && !reD.test(c.value)) {
errors.push('Stock number must be a positive integer.'];
}
}
// deal with errors...
}
Note that in the test:
> barcode == null || barcode == ""
barcode is a string, so the first test will never return true and the second is sufficient if you want to see if it's empty.