I have a form with this filed and by ADD button I can add rows. To remove the rows I have put deleteRow function, but this work only if the checkbox is on the left of the form. The checkbox must be on the right form and when press the delteRow, not work
This is the script:
<form name="books">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<button type="button" onClick="deleteRow('dataTable')"> DEL Book </button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td><input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td><input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td><input type="text" class="form-control" name="book_pages_total">
<td width="51"><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</table>
</form>
Javascript function:
function addRow(tableID) {
var table = document.querySelector('#' + tableID);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {if (i) input.value = '';});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
How to remove the rows when the checkbox is on the right form?
I hope to explain my problem.
Thanks
As pointed out elsewhere, in Roljhon's answer, the problem is the line:
var chkbox = row.cells[0].childNodes[0];
To correct this, you can either change the index from row.cells[0] to the correct index (here it would, as noted in that answer, be 6) or you can make it more flexible, and simply select the appropriate <input> element from the specified <tr> (the row) variable, using the appropriate CSS selector and Element.querySelector()]:
// here we look within the <tr> represented by the 'row' variable:
var chkbox = row
// using Element.querySelector():
.querySelector(
// to find the first (if any) <input> element, with
// its 'type' attribute equal to 'checkbox' and its
// 'name' attribute equal to the string 'chk[]'
// (the square brackets are escaped because otherwise
// they're recognised as part of the CSS selector):
'input[type=checkbox][name="chk\[\]"]'
);
function addRow(tableID) {
var table = document.querySelector('#' + tableID);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {
if (i) input.value = '';
});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.querySelector('input[type=checkbox][name="chk\[\]"]');
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<form name="books">
<button type="button" onClick="addRow('dataTable')">ADD Book</button>
<button type="button" onClick="deleteRow('dataTable')">DEL Book</button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td>
<input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td>
<input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td>
<input type="text" class="form-control" name="book_pages_total">
<td width="51">
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
</table>
</form>
JS Fiddle demo.
References:
CSS:
CSS Attribute Selectors.
JavaScript
Element.querySelector().
Your pointing to a wrong cell cell[0], it points to tthe first cell not the 6th cell where your checkbox is.
Change it to :
var chkbox = row.cells[6].childNodes[0];
Related
I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}
I created a table that can add rows by filling in a form. Every row added to the table, get's a row number. Now I want to delete a certain row by putting in the row number in another input (using a deleteRow-function).
<table id="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
</table>
<form action="" id="form" name="form">
First name: <input type="text" id="fnaam"> <br>
Last name: <input type="text" id="lnaam"><br>
Points: <input type="text" id="points">
</form>
<button type="button" id="addBtn">Voeg toe</button>
Fill in row number: <input type="text" id="deleteRowInput"> <br>
<button type="button" id="deleteBtn">Delete Row</button>
This is the Javascript I use. I created a deleteRow-function, but it's not working yet. Thanks!
var addBtn = document.getElementById('addBtn');
var deleteBtn = document.getElementById('deleteBtn');
addBtn.onclick = addRow;
deleteBtn.onclick = deleteRow;
var rowNumber = 0;
function addRow() {
//getting data from form
var form = document.getElementById('form');
var newData = [];
for(var i = 0; i < form.length; i++) {
newData[i] = form.elements[i].value;
}
if(validateForm() == true) {
rowNumber++;
//Put data in table
var table = document.getElementById('table');
var newRow = table.insertRow();
//Adding rownumber to row
newRow.innerHTML = `<tr><td><i>${rowNumber}</i></td><tr>`;
for(var i = 0; i < 3; i++) {
var newCell = newRow.insertCell(i);
newCell.innerHTML = newData[i];
}
}
form.reset();
}
function deleteRow() {
var table = document.getElementById('table');
var input = document.getElementById('deleteRowInput');
}
//validating form
function validateForm() {
var f = document.getElementById('form');
if(f.fnaam.value == '') {
alert('Please fill in first name!');
return false;
}
if(f.lnaam.value == '') {
alert('Please fill in last name!');
return false;
}
if(f.points.value == '') {
alert('Please fill in points!');
return false;
}
if(isNaN(f.points.value)) {
alert('Points should be a number!')
return false
}
return true;
}
To simplify matters, add a data- attribute to the tr elements containing the respective row number.
Modification in addNumber:
newRow.innerHTML = `<tr data-row-number="${rowNumber}"><td><i>${rowNumber}</i></td><tr>`;
The deleteRow function could look like this:
function deleteRow() {
let table = document.getElementById('table');
let input = document.getElementById('deleteRowInput');
let n_rowToDelete = input.value;
document.querySelector ( 'tr[data-row-number="' + n_rowToDelete + '"]' ).remove();
}
Watch out for:
having 1 table only.
not to delete the last row
... and be aware that after the first call to deleteRow there will neither be a contiguous list of row numbers nor will the row number mirror the position of the row in the sequence of table rows.
Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());
I want to thank you guys for your response and assistance rendered so far, i am greatful but please i wouldn't mind if you don't get tired on me.
Thanks.
Please i need help with my dynamic table, everything seems to be working fine except for my onchange event for each dynamically added row, it only inserts into the first row, but when i select an option from the second added row, the feilds to be updated from the database remains blank.
I used alert to check, and the onchange seems to be working on all rows just that it is only the first row that changes are effected to the required fields. Bellow is my code for your review.
php script at the top of the page that populates select option data from the database
<?php
$query1 = "SELECT * FROM products";
$result1 = mysqli_query($con, $query1);
$options = "";
while($row3 = mysqli_fetch_array($result1))
{
$options = $options."<option value='$row3[1]'>$row3[2]</option>";
}
?>
My Javascript
<SCRIPT language="javascript">
//function that increases the table row
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
//function that reduces the table row
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
//function that handles the summing of each row & all last column
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox12 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox23 = mainRow.querySelectorAll('[id=descript')[0].value;
var myBox1 = mainRow.querySelectorAll('[id=uprice')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var multiplier = Number(myBox2) || 0;
var myResult1 = myBox1 * multiplier;
var mresult = myResult1.toFixed(2);
total.value = mresult;
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total2 = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
console.log(total2);
$("#sumtotal").val(total2.toFixed(2));
return total2;
}
//function that gets the amount due(balance left)
function amountDue() {
var amount = parseFloat($("#sumtotal").val());
var paidd = parseFloat($("#paid").val());
var balance = amount - paidd;
$("#due").val(balance.toFixed(2));
$("#due2").val(balance.toFixed(2));
//return total2;
}
//function that updates #uprice and #descript from the data base onchange of the select box
function get_item(elementID){
$.ajax({
method:"POST",
url:"get_price.php",
data:{item2:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
//$('#descript').val(data);
$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
$('#descript').val(data);
}else{
alert('Description not available');
}
}
});
}
</SCRIPT>
My html code
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Sub Total (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" />
</td>
<td>
<select required="required" name="item" onchange="get_item('row_0')" id="item" placeholder="Item">
<option value="0"> select an item</option>
<?php echo $options;?>
</select>
</td>
<td>
<input type="text" required="required" class="small" name="descript" id="descript" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="uprice[]" oninput="calculate('row_0')" id="uprice" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="0">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" value="0.00" readonly="readonly" style="background-color: white">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" class="butto" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/>
Already mentoined here, but still: How to submit form on change of dropdown list? . When user submits form, use php fetch from databse, with isset($_POST['name'])
I was able to fix it with making the some changes in my get_item() javascript function
function get_item(dropDown){
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:dropDown.value},
success:function(data){
alert(data);
if(data!='0'){
$($(dropDown).parents('tr')[0]).find('input#descript').val(data);
//$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
}
thanks everyone.
this is the form
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td><label>should be auto increment(like (name1, name2, name3 ...))</label>
<input type="text" required="required" name="DONINID[]" value=""></td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
</form>
this is the script to add more => script.js:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 20){ // limit the user from creating fields more than your limits
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;
}
}else{
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Now the idia is how to change the label name too as we add more input box it's should be auto increment like:
name1, name2, name3, name3 and when we add it should show us.
thanks in advance.
Add a variable that tracks the next # to use and append it to the contents and name every time you add one.
HTML
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td>
<label>Name 1:</label>
<input type="text" required="required" name="name1" />
</td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
JavaScript
var nextName = 2;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 20) { // limit the user from creating fields more than your limits
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 = '<label>Name ' + nextName + ':</label>' +
'<input type="text" required="required" name="name' + nextName + '" />';
nextName++;
}
} else {
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Demo: http://jsfiddle.net/BenjaminRay/4jnw0t09/