I'm trying to make a little program that uses generated (dynamically) tables, I will explain an example:
I have a blank page with only and input (number type) and a div:
<input id='numoftables' type='number'>
<div id='tablescontainer'></div>
I need create N tables with the following structure:
<table>
<tr>
<td>
<div style='text-align:left;'>
<h3>
<span class='label label-default'>Table #N</span>
</h3>
</div>
</td>
<td>
<input id='secondNum' type='number' class='form-control input-md' value='1'>
</td>
</tr>
</table>
<div class='table-responsive text-left'>
<table id='tableN' class='table table-striped condensed'>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
</tr>
</thead>
<tbody>
<tr>
<td align='middle'>
<b>M</b>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<div class='input-group date' id='fecha'>
<input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required>
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</div>
</td>
<td align='middle'>
<img class='delete' src='img/delete.png' >
</td>
</tr>
</tbody>
</table>
</div>
<hr>
It's generate something similar of this (with setting a value of 3 on input with id 'numoftables'):
But I want to make dynamic elements (with dynamic id's), please see this:
Red boxes will have the dynamic number, 1 to N; N is the value of the input with id 'numoftables'.
Green boxes represents the numbers of rows (I call this number, M) of the tableN.
How can I to generate all of this dynamically :(?
I have a crazy code, like this:
$("#tablescontainer").html(null);
for (i=1;i<=$("#numoftable").val();i++)
{
$("#tablescontainer").append("<table><tr><td><div style='text-align:left;'><h3><span class='label label-default'>Table #N</span></h3></div></td><td style='position:relative;top:7px !important;left:8px;'><input id='secondNum' type='number' style='width:64px;' class='form-control input-md' value='1'></td></tr></table><div class='table-responsive text-left'><table id='tableN' class='table table-striped condensed'><thead><tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th><th>Col 6</th></tr></thead><tbody><tr><td align='middle'><b>M</b></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><div class='input-group date' id='fecha'><input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required><span class='input-group-addon'><span class='glyphicon glyphicon-calendar'></span></span></div></td><td align='middle'><img width='20' class='delete' src='img/delete.png' ></td></tr></tbody></table></div><hr><script>$('#numcarr"+i+"').click(function(e){$('#tabla"+i+" > tbody:last').html(null);for (j=1;j<=$(\"#numcarr"+i+"\").val();j++){$('#tabla"+i+" > tbody:last').append('<tr><td align=\"middle\"><b>"+i+"</b></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><div class=\"input-group date\" id=\"fecha\"><input id=\"fechainput\" maxlength=\"10\" data-date-format=\"DD/MM/YYYY\" type=\"date\" class=\"form-control\" placeholder=\"Fecha DD/MM/AAAA\" required><span class=\"input-group-addon\"><span class=\"glyphicon glyphicon-calendar\"></span></span></div></td><td align=\"middle\"><img width=\"20\" class=\"delete\" onclick=\"$(this).parent().parent().remove()\" src=\"img/delete.png\"></td></tr>')}});</script>");
}
I don't know how can I solve this, write less code, make it dynamically :c
Thanks!
see the result in by inspect the table and secondNum: jsfiddle
jQuery
$(function(){
$("#numoftables").on("change", function(){
$("#tablescontainer").html("");
var num = $(this).val();
var table = $("#copy").html();
for (var i=1; i <= num; i++){
var newTable = table.replace("secondNum", "id='secondNum"+i).replace("uniqueTable", "uniqueTable"+i);
$("#tablescontainer").append(newTable);
}
});
});
CSS
#copy{
display: none;
}
Now you have to do other things in the similar fashion, like showing
the the table number. use a different id which may not use in the
content and replace it in the jquery.
Related
I have been facing a problem that I have been looking everywhere for a soultion.
I want to make a page where you can insert new rows to a form table, then use these values to insert into database.
Here is an image of how the page I want to make will look like. sales form
The idea behind the page is that one receipt id will be generated and inside there can be many items that users can add, hence the multiple rows.
Here is the code for the form page.
<?php
include('session.php');
?>
<?php
$ItemID = "ItemID";
$ItemName = "ItemName";
$UnitPrice = "UnitPrice";
$sql = "SELECT ItemID,ItemName,UnitPrice FROM Item";
$result = $db->query($sql);
?>
<html>
<head>
<title>Add Sales</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="text-center">
<h1>Add new Sales Record</h1>
</div>
<div class="container">
<button class="w3-button w3-black w3-round-large">Back</button>
</div>
<div class="container" align="right">
<table class="table-sm">
<tbody>
<tr class="table-primar">
<th scope="col" style="padding-right: 50px;">ItemID</th>
<th scope="col" style="padding-right: 50px">ItemName</th>
<th scope="col">UnitPrice</th>
</tr>
<?php
while($rows = $result->fetch_assoc()) {
?>
<tr class="contents">
<td><?php echo $rows[$ItemID]; ?></td>
<td><?php echo $rows[$ItemName]; ?></td>
<td><?php echo $rows[$UnitPrice]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<hr>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
ItemID
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Price Sold
</th>
<th class="text-center">
Branch ID
</th>
<th class="text-center">
EmployeeID
</th>
<th class="text-center">
MemberID
</th>
</tr>
</thead>
<tbody>
<form action="addsales.php" method="post">
<tr id='addr0'>
<td>
<input type="text" name='item[][itemid]' placeholder='ItemID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][amount]' placeholder='Amount' class="form-control"/>
</td>
<td>
<input type="text" name='item[][pricesold]' placeholder='PriceSold' class="form-control"/>
</td>
<td>
<input type="text" name='item[][branchid]' placeholder='BranchID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][employeeid]' placeholder='EmployeeID' class="form-control"/>
</td>
<td>
<input type="text" name='item[][memberid]' placeholder='MemberID' class="form-control"/>
</td>
</tr>
<tr id='addr1'></tr>
<input class="w3-button w3-black w3-round-large" type="submit" name='submit' value="Submit"/>
</form>
</tbody>
</table>
</div>
</div>
<button id="add_row" class="w3-button w3-black w3-round-large" style="position: absolute; right: 130px;">New row</button>
</div>
<script type="text/javascript">
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('disabled',true);
$('#addr' + i).html("<td><input name='item[][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item[][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item[][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item[][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item[][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item[][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
</script>
</body>
</html>
The values will be handled in another php page.
<?php
include('session.php');
print_r($_POST);
$ItemIDs = $_POST['itemid'];
$PriceSolds = $_POST['pricesold'];
$QtySolds = $_POST['amount'];
$Date = date("Y-m-d h:i:sa");
$BranchIDs = $_POST['branchid'];
$EmployeeIDs = $_POST['employeeid'];
$MemberIDs = $_POST['memberid'];
$size = sizeof($ItemIDs);
$sql2 = "INSERT INTO Receipt_seq VALUES (NULL);";
$db->query($sql2);
for($i = 0; $i < $size; $i++ ){
$ItemID = $ItemIDs[$i];
$PriceSold = $PriceSolds[$i];
$QtySold = $QtySolds[$i];
$BranchID = $BranchIDs[$i];
$EmployeeID = $EmployeeIDs[$i];
$MemberID = $MemberIDs[$i];
$sql = "INSERT INTO Receipt (ItemId,PriceSold,QtySold,RDate,BranchID,EmployeeID,MemberID) VALUES ('{$ItemID}', '{$PriceSold}', '{$QtySold}','{$Date}','$BranchID','$EmployeeID','$MemberID')";
$db->query($sql);
}
?>
The Id for the receipt will be automatically generated using a trigger system. The only problem I have right now is that I can send in one row data just fine. But the moment I add a second row, it gives me an error Undefine index .... I tried to use print_r($_POST); to see what is happening and this is the result. When I submitted one row of data it looked fine one row But when I added the second row it gave me this error more than one row error. I am a beginner at making website so I am not sure what I am doing is correct or not. Please help, thank you. I added and image of what my sales page will look like so you might have a better understanding of what I am trying to do Sales page.
Just to clarify points above, you MUST set the inputs with attribute readonly NOT disabled so that the previous input rows get included.
Then just follow what I said in the comments by adding (concatenating) the index into the dynamically added input rows:
$('#addr' + i).html("<td><input name='item["+i+"][itemid]'
// ^ add the dynamic index here
Sidenote: Don't forget to wrap the table with the form tag
I'll just add the important bits, so all in all:
a. Form tag before table tag
<div class="col-md-12 column">
<form action="" method="post"> <!-- this -->
<table class="table table-bordered table-hover" id="tab_logic">
b. change to readonly instead of disabled attribute and add the index in the "add row"
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('readonly',true);
$('#addr' + i).html("<td><input name='item["+i+"][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
Full code:
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
$('#addr'+(i-1)).find('input').attr('readonly',true);
$('#addr' + i).html("<td><input name='item["+i+"][itemid]' placeholder='ItemID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][amount]' placeholder='Amount' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][pricesold]' placeholder='PriceSold' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][branchid]' placeholder='BranchID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][employeeid]' placeholder='EmployeeID' class='form-control input-md'/></td><td><input type='text' name='item["+i+"][memberid]' placeholder='MemberID' class='form-control input-md'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form action="" method="post">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
ItemID
</th>
<th class="text-center">
Amount
</th>
<th class="text-center">
Price Sold
</th>
<th class="text-center">
Branch ID
</th>
<th class="text-center">
EmployeeID
</th>
<th class="text-center">
MemberID
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
<input type="text" name='item[0][itemid]' placeholder='ItemID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][amount]' placeholder='Amount' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][pricesold]' placeholder='PriceSold' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][branchid]' placeholder='BranchID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][employeeid]' placeholder='EmployeeID' class="form-control"/>
</td>
<td>
<input type="text" name='item[0][memberid]' placeholder='MemberID' class="form-control"/>
</td>
</tr>
<tr id='addr1'></tr>
<input class="w3-button w3-black w3-round-large" type="submit" name='submit' value="Submit"/>
</tbody>
</table>
</form>
</div>
</div>
<button id="add_row" class="w3-button w3-black w3-round-large" style="position: absolute; right: 130px;">New row</button>
</div>
I currently have a table with a checkbox and product name on one side, then a quantity input field on the other side. By default, the quantity field is disabled, but I would like to enable it only if its corresponding product is checked.
I'm still new to jQuery and a bit stuck on this, so this is a best I could come up with:
$(document).ready(function(){
//enable quantity field if product is selected
$("input[name='quantity']").prop('disabled', 'true');
$(".product").on('click', function(){
$next = $(this).next();
$next.prop('disable', 'false');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="products">
<thead>
<tr>
<th>Product Name</th>
<th width="150">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
</tbody>
</table>
You have duplicate IDs for input element. IDs must be unique. you can rather use classname and then use class selector to target element by classname.
And your solution is not working because
1) you have wrong selector to target next input element. you need to traverse to closest tr and then find element with name quantity in it.
2) You are setting wrong property. you need to use disabled instead of disable :
$(".product").change(function(){
$next = $(this).closest('tr').find('[name=quantity]');
$next.prop('disabled', this.checked);
});
Working Demo
$(".product").on('change', function(){
$(this).closest('tr').find("input[name='quantity']").prop('disabled',!this.checked);
});
To get what you want you can use this two DOM traversal methods .closest() or .parents()
$(document).ready(function(){
//enable quantity field if product is selected
$("input[name='quantity']").prop('disabled', true);
$(".product").change(function(){
$(this)
.parents('td')
.next()
.find('input')
.prop('disabled', !$(this).is(":checked"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="products">
<thead>
<tr>
<th>Product Name</th>
<th width="150">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity'></td>
</tr>
<tr>
<td><input type='checkbox' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' ></td>
</tr>
<tr>
<td><input type='checkbox' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' ></td>
</tr>
</tbody>
</table>
First, fix your code so that you don't have duplicate IDs. It won't prevent the code from running, but it's not good HTML.
Here's how I would write the script:
$(document).ready(function(){
// Enable quantity field if product is selected
$("input[name='quantity']").prop('disabled', true);
$(".product").on('click', function() {
// Get reference to the text field in the same row with the name "quantity"
var $next = $(this).closest('tr').find('input:text[name="quantity"]');
// Enable the text field if the checkbox is checked, disable it if it is unchecked
$next.prop('disabled', ! $(this).is(':checked'));
});
});
That will enable AND disable it as required.
This approach does what you are looking for.
$(function(){
$(':checkbox').change(function(){
var prodId = $(this).data('productidckbx');
if($(this).is(':checked')) {
$('#prodquantity-' + prodId).prop('disabled', false);
} else {
$('#prodquantity-' + prodId).prop('disabled', true);
}
});
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<table id="products">
<thead>
<tr>
<th>Product Name</th>
<th width="150">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='checkbox' id='product-1' name='product' data-productidckbx='1'>
<label>Product</label>
</td>
<td><input type='text' placeholder='0' name='quantity' id='prodquantity-1' disabled="disabled"></td>
</tr>
<tr>
<td><input type='checkbox' id='product-2' class='product' name='product' data-productidckbx='2'>
<label>Product</label>
</td>
<td>
<input type='text' placeholder='0' name='quantity' id='prodquantity-2' disabled="disabled"></td>
</tr>
<tr>
<td>
<input type='checkbox' id='product-3' class='product' name='product' data-productidckbx='3'>
<label>Product</label>
</td>
<td>
<input type='text' placeholder='0' name='quantity' id='prodquantity-3' disabled="disabled">
</td>
</tr>
</tbody>
</table>
I am doing some calculations in my php script. its done in jquery/javascript. I have a small issue with my following script. The actual scenario is its getting the Total INR value, In the Add (%) field i add the percentage. So the system calculates and add this percentage to the Total Value. Its perfect in the first row of record. But in the second row, its taking the value of the first row. Iam making a small mistake. My script is following. Pls help me on this.
<script type='text/javascript' src='http://code.jquery.com/jquery-2.1.3.js'></script>
<script type='text/javascript'>
//<![CDATA[
function getIndexedElement(item, index) {
if (item.length) {
if (index < item.length) {
return item[index];
} else {
return false;
}
} else {
if (index === 0) {
return item;
}
}
return false;
}
function isNum(value) {
return 123;
}
function calcTotals() {
var grandTotal = 0;
var i = 0;
while (getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i)) {
add_percentageObj = getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i);
addon_valueObj = getIndexedElement(document.forms['cart'].elements['addon_value[]'], i);
total_inr_valueObj = getIndexedElement(document.forms['cart'].elements['total_inr[]'], i);
totalObj = getIndexedElement(document.forms['cart'].elements['add_value[]'], i);
priceunitObj = getIndexedElement(document.forms['cart'].elements['price_unit[]'], i);
qtyObj = getIndexedElement(document.forms['cart'].elements['qty[]'], i);
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = Math.round((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1;
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
//c.value=Math.round((b.value/100) *a.value ).toFixed(2);
} else if (addon_valueObj.value) {
totalObj.value = Math.round((addon_valueObj.value * 1) + total_inr_valueObj.value * 1);
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
} else {
totalObj.value = Math.round((addon_valueObj.value * 1) + total_inr_valueObj.value * 1);
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
}
i++;
}
document.getElementById('grand_total').value = grandTotal;
return;
}
</script>
</head>
<body>
<form name='cart' method='post' class='single' action='generate_quot_cust_edititems_save_complete.php?tender_id=14'>
<input type='hidden' name='sum_input' id='sum_input' value=''>
<div align="center">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr bgcolor="#E6E6FA">
<td width=4%>Qty</td>
<td width=5%>Unitprice</td>
<td width=8%>Total INR</td>
<td width=5%>Add (%)</td>
<td width=7%>Add Value</td>
<td width=6%>Total Value</td>
<td width=8%>Total</td>
<td width=8%>Price/Unit</td>
</tr>
</table>
</div>
<div align="center" class="base">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr>
<td width='4%'>
<input size='1' class='qty' type='text' name='qty[]' id='qty[]' value='20' readonly/>
</td>
<td width='5%'>
<input size='5' type='text' name='unitprice[0]' value='678.000' readonly/>
</td>
<input size='4' type='hidden' id='total_inr[]' name='total_inr[]' value='883332.313' />
<td width='8%'>
<input size='10' type='text' id='total_inr[]' name='total_inr[]' value='883332.300' />
</td>
<td width='5%'>
<input class='' size='4' type='text' id='add_percentage[]' name='add_percentage[]' value='0' onchange='calcTotals()'>
</td>
<td width='7%'>
<input class='txt' type='text' size='7' id='addon_value[]' name='addon_value[]' value='0' onchange='calcTotals()'>
</td>
<td width='6%'>
<input class='total' data-value='883332' size='6' type='text' id='add_value[]' name='add_value[]' value=''>
</td>
<input type="hidden" class="inrvalue" id="inrvalue" name="inrvalue" value="65.1425">
<input type="hidden" class="deptip" id="dept-input" />
<input type="hidden" class="priceip" id="price-input" />
<td width="8%">
<input size="9" type="text" data-value="" name='total1[]' id='total1[]' value="16271.993" readonly class="total1" />
</td>
<td width='8%'>
<input class='price_unit' size='7' type='text' id='price_unit[]' name='price_unit[]' value='813.600' readonly>
</td>
</tr>
</table>
</div>
<div align="center" class="base">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr>
<td width='4%'>
<input size='1' class='qty' type='text' name='qty[]' id='qty[]' value='360' readonly/>
</td>
<td width='5%'>
<input size='5' type='text' name='unitprice[1]' value='569.000' readonly/>
</td>
<td width='8%'>
<input size='10' type='text' id='total_inr[]' name='total_inr[]' value='13343789.700' />
</td>
<td width='5%'>
<input class='' size='4' type='text' id='add_percentage[]' name='add_percentage[]' value='0' onchange='calcTotals()'>
</td>
<td width='7%'>
<input class='txt' type='text' size='7' id='addon_value[]' name='addon_value[]' value='0' onchange='calcTotals()'>
</td>
<td width='6%'>
<input class='total' data-value='883332' size='6' type='text' id='add_value[]' name='add_value[]' value=''>
</td>
<td width="8%">
<input size="9" type="text" data-value="" name='total1[]' id='total1[]' value="16000.803" readonly class="total1" />
</td>
<td width='8%'>
<input class='price_unit' size='7' type='text' id='price_unit[]' name='price_unit[]' value='44.447' readonly>
</td>
</tr>
</table>
</div>
<table width='100%'>
<tr>
<td width='3%'> </td>
<td width='4%'> </td>
<td width='17%'> </td>
<td width='5%'> </td>
<td width='5%'> </td>
<td width='6%'> </td>
<td width='5%'> </td>
<td width='7%'> </td>
<td width='8%'> </td>
<td width='5%'> </td>
<td height=35><b>Grand Total: <input type='text' style='font-weight: bold' name='gTotal' id='grand_total' value='1766664.000' readonly /></b></td>
</tr>
<tr>
</table>
<br>
</div>
<table border='0' width='13%'>
<td>
<input type='submit' value='--Save Data--' />
</td>
Element ID's have to be unique. If you refer to an element by id, and there are multiple elements with the same ID, then you likely only going to get the first one back. Also, I suspect that elements["name"] does not give an array back, but a unique element.
Instead try using something like this instead:
cartForm = document.forms['cart'];
...
add_percentageObj = getIndexedElement(cartForm.getElementsByName('add_percentage[]'), i);
An element name does not have to be unique. I see that you are already using both id and name anyhow on your elements.
Also I would suggest writing a function like this (untested):
function getCartElement(name, index) {
namedElements = document.forms['cart'].getElementsByName(name);
if (index >= namedElements.length) return null;
return namedElements[index];
if (item.length) {
}
Anyway, the rest of your code would look like something like this:
while (getCartElement('add_percentage[]', i) != null) {
add_percentageObj = getCartElement('add_percentage[]', i);
addon_valueObj = getCartElement('addon_value[]', i);
...
Note that I made sure that your function returns a consistent datatype, not one time boolean, another time an element instance ... this does mean however that you will require to check for null values.
Reference:
getElementsByName
getElementsById
elements
Also read this other stackoverflow article
I have a form which has same products but with different attributes.
The form looks something similar to this:
<form>
<table>
<tr>
<td> Line-1 </td>
<td> <input type='text' name='ítem[1][Size]'</td>
<td> <input type='text' name='ítem[1][Color]'</td>
<td> <input type='text' name='ítem[1][Price]'</td>
</tr>
<tr>
<td> Line-2 </td>
<td> <input type='text' name='ítem[2][Size]'</td>
<td> <input type='text' name='ítem[2][Color]'</td>
<td> <input type='text' name='ítem[2][Price]'</td>
</tr>
<tr>
<td> Line-3 </td>
<td> <input type='text' name='ítem[3][Size]'</td>
<td> <input type='text' name='ítem[3][Color]'</td>
<td> <input type='text' name='ítem[3][Price]'</td>
</tr>
<tr>
<td> Line-4 </td>
<td> <input type='text' name='ítem[4][Size]'</td>
<td> <input type='text' name='ítem[4][Color]'</td>
<td> <input type='text' name='ítem[4][Price]'</td>
</tr>
</table>
</form>
PHP Sample Code:
for($i = 0;$i < count($_POST);$i++){
var_dump($_POST[$i]);
}
Error:
Notice: Undefined offset: 0 in C:\xampp\htdocs\test\testing.php on line 5
If I was to remove item[2] dynamically using js, on submit php would throw an error because it cant find number 2. How could go about this?
Perhaps I'm not doing it right?
In your PHP Code, use foreach as has been suggested:
foreach($_POST['item'] as $item){
echo $item['Size'] . "<br />";
echo $item['Color'] . "<br />";
echo $item['Price'] . "<br />";
echo "<hr />"
}
EDIT:
Another question how would i go about re-changing row numbers once I
deleted row number 2?
This is done in JS or JQuery. Something like:
var i = 1;
$.each($("tr"), function(){
$(this).next("input[name*='Size']").attr("name", "item[" + i + "][Size]");
$(this).next("input[name*='Color']").attr("name", "item[" + i + "][Color]");
$(this).next("input[name*='Price']").attr("name", "item[" + i + "][Price]");
i++;
});
EDIT:
$(document).ready(function(){
$("#add").click(function(){
var currentValue = parseInt($("#hide").val())+1;
$("#Recipe_table").append("<tr><td><input type='text' name='name[]'/></td><td><input type='text' name='quantity[]'/></td><td><input type='text' name='measure[]'/></td></tr>");
$("#hide").val(currentValue);});
$("#remove").click(function(){
var currentValue = parseInt($("#hide").val())-1;
if ($("table tr").length != 1) {
$('#Recipe_table tr:last').remove();}});
});
Add and Deletion works.
My question is, I dont want to delete all rows or ill end up deleting my headers aswell until there was no table in the first place.
Secondly, The value doesnt decrement when i remove, i simply copied above since it works and adds the value of the hidden field.
Plus, Is there a better way of setting the value, The above approach just increments without hesitation like for example.
Plus how i prevent it from not reverting back to its original value when i submit and back one page.
I don't think the solution you got for counting the number of <td> is a good solution,
use
numberOfTds = $("#table").children('tr').children('td').length;
You have to close your elements
<table id='table'>
<th colspan='3'> Table</th>
<tr>
<td><input type='text' name='name1[]'/></td>
<td><input type='text' name='name2[]'/></td>
<td><input type='text' name='name3[]'/></td>
</tr>
</table>
You haven't closed your cell or table tags. Here's the corrected html. I had to assume where you wanted your final input tag...
<html>
<body>
<table id='table'>
<th colspan='3'> Table</th>
<tr>
<td><input type='text' name='name1[]'/></td>
<td><input type='text' name='name2[]'/></td>
<td><input type='text' name='name3[]'/></td>
</tr>
</table>
<input type='hidden' id='put int on how many rows added'/>
</body>
</html>
You look like a beginner to HTML, CSS and JS(JQuery) so a few rules. Structure your code like so:
<table id='table'>
<th colspan='3'>Table</th>
<tr>
<td><input type='text' name='name1'/></td>
<td><input type='text' name='name2'/></td>
<td><input type='text' name='name3'/></td>
</tr>
</table>
<input type='hidden' name="name4" value="The Text you Want to Store"/>
..but you still need to learn HTML before you can effectively use JS. With JQuery to can get the values of the table elements using:
$('[name="name1"]').val();
and set the value using:
$('[name="name1"]').val("NewValue");
Look at the website w3schools.com for HTML and JS help and jquery.com for learning jquery
Close your </td> tags
<table id='table'>
<th colspan='3'> Table</th>
<tr><td><input type='text' name='name1[]'/></td>
<td><input type='text' name='name2[]'/></td>
<td><input type='text' name='name3[]'/></td>
</tr>
Edit: this will also work
<table id='table'>
<th colspan='3'> Table</th>
<tr><td/><input type='text' name='name1[]'/>
<td/><input type='text' name='name2[]'/>
<td/><input type='text' name='name3[]'/>
</tr>
This is an example how the rows can be added dynamically
HTML
<table id='table'>
<th colspan='3'> Table</th>
<tr><td><input type='text' name='name1[]'/></td>
<td><input type='text' name='name2[]'/></td>
<td><input type='text' name='name3[]'/></td>
</tr>
</table>
<input type="button" id="btn" value="add"/>
Script
$(document).ready(function(){
$("#btn").click(function(){
$("#table").append(" <tr><td><input type='text' name='name1[]'/></td><td><input type='text' name='name2[]'/></td> <td><input type='text' name='name3[]'/></td></tr>");
});
});
Demo
Edit
<input type='hidden' id='hide'/>
var currentValue= parseInt($("#hide").val())+1;;
$("#hide").val(currentValue);