When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.
Related
I am adding rows in table and deleting, this works fine. using oninput="" event i am also able to calculate the total cost by calling javascript function.
Now, the moment i add <form></form>, neither am able to add rows nor moving any forward. I am new to javascript, and have no clue what is going on. please help somebody.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i <= arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Inside the form tags buttons tend to do the default action which is submit.
So change your button from,
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
to
<input type="button" onclick="myCreateFunction()" value="Create row">
<input type="button" onclick="myDeleteFunction()" value ="Delete row">
You have to add Input tag instead of button tag. Because button tag in form specifies default submit event on-click so your form submitted when you add any row and also refresh.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<input type="button" onclick="myCreateFunction()" value="Create row" />
<input type="button" onclick="myDeleteFunction()" value="Delete row" />
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i < arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Hi iam able to add rows dynamically from the table below using javascript but the onchange function fired on the select box only works on the first row added how do you make it work for every row being added.Thanks.
<html>
<body>
<link href="style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src='script.js'></script>
<table id="addProducts" border="1">
<tr>
<td>POI</td>
<td>Quantity</td>
<td>Price</td>
<td>Product</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input size=25 type="text" id="price" readonly=true/></td>
<td>
<select name="selRow0" class="products">
<option value="value0">Product 1</option>
<option value="value1">Product 2</option>
</select>
</td>
<td><input type="button" id="delProducts" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmoreProducts" value="AddMore" onclick="insRow()"/></td>
</tr>
</table>
<div id="shw"></div>
</body>
</html>
$(function () {
$("select.products").on("change", function () {
var selected = $(this).val();
$("#price").val(selected);
})
});
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('addProducts').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('addProducts');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the first cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// append the new row to the table
x.appendChild(new_row);
}
I've updated your code. This should work now. Look at this jsfiddle:
JS:
$(function () {
$(document).on('change', 'select.products', function(){
var selected = $(this).val();
$(this).parents('tr').find('.price').val(selected);
});
$(document).on('click', '.addProduct', function(){
var ele = $(this).parents('tr').clone();
ele.find('input[type=text]').val('');
$(this).parents('tr').after(ele);
});
$(document).on('click', '.delProduct', function(){
if($(this).parents('table').find('tr').length > 2) {
$(this).parents('tr').remove();
}
});
});
Also I've updated your HTML:
<td><input size=25 type="text" class="lngbox" readonly=true/></td>
<td><input size=25 type="text" class="price" readonly=true/></td>
<td><input type="button" class="delProduct" value="Delete" /></td>
<td><input type="button" class="addProduct" value="AddMore" /></td>
Try this,
$("select.products").on("change", function(){
var selectedValue = $(this).val();
var td = $(this).parent();
(((td).parent()).children()[2].getElementsByTagName("input")[0]).value = selectedValue;
});
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to create a table using jquery. The number of rows the table will be determined from input box. The number of columns are known. After submitting that, a table gets generated. Tried creating a fiddle.
Am very new to jquery . Not sure how to proceed.
Fiddle link here
<form>
Number of rows to be generated
<br>
<input type="number" id="table-row-num" value="3">
<button>Submit</button>
</form>
<div id="table-gen">
<p>Table generated here after clicking submit</p>
<table cellpadding="1" cellspacing="1" border="1">
<tr>
<td>1</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>3</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
</table>
</div>
This is your fiddle updated:
http://jsfiddle.net/fpd8dwtw/17/
This is the jquery code:
$("#submitButton").click(function() {
var table = $("#resultTable");
var rowNum = parseInt($("#table-row-num").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
I wish you luck with implementation. :)
Edit:
If you want to allow number of rows to be on range between minimum and maximum number the best solution is to use native html 5 validation.
This is jsfiddle:
http://jsfiddle.net/fpd8dwtw/20/
Say you gave an id to your <table> element
<table cellpadding="1" cellspacing="1" border="1" id="tableElement">
and an onclick attribute to your button
<button onclick="addRows()">Submit</button>
your (pure) Javascript should look like this :
function addRows() {
var table = document.getElementById('tableElement');
var rows = parseInt(document.getElementById('table-row-num').value);
for (var i = 1; i <= rows; i++) {
var tr = document.createElement('tr');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var input1 = document.createElement('input');
var input2 = document.createElement('input');
input1.type = "text";
input2.type = "text";
input1.placeholder = "Text goes here...";
input2.placeholder = "Text goes here...";
cell1.innerHTML = i.toString();
cell2.appendChild(input1);
cell3.appendChild(input2);
tr.appendChild(cell1);
tr.appendChild(cell2);
tr.appendChild(cell3);
table.appendChild(tr);
}
}
Now I'm sure the jquery code would be a lot smaller but trust me, your browser would respond a lot faster to pure Javascript.
you can use append of jQuery.
var count = 30;
var row = "<tr><td>1</td><td>2</td><td>3</td></tr>";
for(var i=0; i< count; i++){
$('#tableId tbody').append(row);
}
<table id="tableId"></table>
I have created a fiddle for you. Have a look
https://jsbin.com/hoyetu/edit?html,js,output
$('button').on('click', generate);
function generate(e) {
var rows = $('#table-row-num').val();
var html = '';
for (var i = 0; i < rows; i++) {
html += '<tr>' +
'<td>' + (i + 1) + '</td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'</tr>';
}
$('table').html(html);
}
http://jsfiddle.net/fpd8dwtw/13/
$("#createTable").on("click", function (event){
event.preventDefault();
var noOfRows = $("#table-row-num").val();
var noOfCols = 3; // fixed columns as you mentioned in the question
var fragment = document.createDocumentFragment();
var oTable = document.createElement("table");
for(var i =0; i < noOfRows; i++){
var oTr = document.createElement("tr");
for(var j=0; j < noOfCols; j++){
var oTd = document.createElement("td");
oTd.innerHTML = "put your content here";
oTr.appendChild(oTd);
}
oTable.appendChild(oTr);
}
$("#table-gen").html(oTable);
});
When i click + sign, new row will be cloned. I have already done the some work, for that copy the first row value and placed that value in cloned row. Everything will be fine, but file upload values are not palced in new row.
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code1').value;
var product=document.getElementById('product1').value;
var first=document.getElementById('first1').value;
var additn=document.getElementById('additn1').value;
var qty=document.getElementById('qty1').value;
var oldfname=document.getElementById('oldfilename1').value;
var lastIndex = oldfname.lastIndexOf("\\");
if (lastIndex >= 0) {
oldfname = oldfname.substring(lastIndex + 1);
}
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
inp1.setAttribute('readonly', 'readonly');
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
inp2.setAttribute('readonly', 'readonly');
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = first;
inp3.setAttribute('readonly', 'readonly');
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = additn;
inp4.setAttribute('readonly', 'readonly');
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = qty;
inp5.setAttribute('readonly', 'readonly');
var inp6 = new_row.cells[5].getElementsByTagName('input')[0];
inp6.id += len;
//inp6.value = oldfname;
inp6.setAttribute("type", "file");
var button = new_row.cells[6].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function() {editRow(this)};
var button = new_row.cells[6].getElementsByTagName('input')[1];
button.value = "-";
button.disabled=false;
x.appendChild( new_row );
document.getElementById('code1').value='';
document.getElementById('product1').value='';
document.getElementById('first1').value='';
document.getElementById('additn1').value='';
document.getElementById('qty1').value='';
document.getElementById('oldfilename1').value='';
document.getElementById('code1').focus();
}
html code is,
<table id="scrolltable" class="table">
<thead>
<tr>
<th>Code</th>
<th>Product</th>
<th>First</th>
<th>Add</th>
<th>Qty</th>
<th>File</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr><td><input type="text" name="code" id="code1" /> </td>
<td><input type="text" name="product[]" value="" class="input-medium" id="product1" /> </td>
<td><input type="text" name="first[]" value="" class="input-small" id="first1"/></td>
<td><input type="text" name="additn[]" value="" class="input-small" id="additn1" /></td>
<td><input type="text" name="qty[]" value="" class="input-small" id="qty1" /></td>
<td><input type="file" name="oldfilename[]" value="" class="input-small" id="oldfilename1" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)" disabled />
</td></tr>
</tbody>
</table>
my fiddle file is http://jsfiddle.net/c9dccnua/
I am having a table it contains only one row. Row has a lot of elements like textboxs and buttons. When I click the button the table row will be cloned using append() function. My problem is when I click the button I want to increment the textbox and button id. How can I do this?
Example HTML:
<tr id="items:1">
<td id="id">
<input type="text" id="price:1" name="price" value="" size="6" readonly="readonly" />
</td>
<td id="id">
<input type="text" id="quantity:1" name="quantity" size="10" align="middle" onblur="totalprice(this)" />
</td>
<td id="id">
<input type="text" id="total:1" name="total" size="10" value="0" readonly="readonly" align="middle" />
</td>
<td id="id">
<input type="button" onclick="cloneRow()" id="button:1" value="ADD" />
</td>
</tr>
Example JavaScript:
function cloneRow() {
var row = document.getElementById("items:1");
var table = document.getElementById("particulars");
var clone = row.cloneNode(true);
var rowId = "items:" + a.toString();
clone.id = rowId;
var tabledataid = document.getElementById("id");
var inputtext = tabledataid.getElementsByTagName("input");
var inputtextid = inputtext[a];
var changeInputTextid = "price:" + b.toString();
inputtextid.id = changeInputTextid;
alert(changeInputTextid);
table.appendChild(clone);
a++;
}
A fiddle
Create a function to add rows and just use the indexes of text boxes and columns correctly
function insertRow() {
var x = document.getElementById('ttable');
var new_row = x.rows[0].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
x.appendChild(new_row);
}