How to assign an incremental id while appending rows in table? - javascript

Just need your help.
My problem is I am creating a dynamic form. In my form there is a button and below that is a table.
The scenario is:
1. The user will click the the button
2. After clicking the button the table row will dynamically added. Inside my row there is a textbox
I can do that but how can i do the process after the user click the button. The row will append together with a textbox. But I want to assign a unique ID in a textbox. In my case I want to do this incremental.
Here's my js:
$(document).ready(function(){
$("[data-item]").on('click',function(){
$("#grid1 tbody").append("<tr><td><input type='text' value='123' style='width:100px' id='' /></td></tr>");
});
});
Here's my table:
<input type="button" name="add" data-item="123" value="ADD" class="test" id="test" />
<table id="grid1" border="1" style="width: 40%">
<thead>
<tr>
<th style="text-align: center;">CODE</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here's the fiddle:
http://jsfiddle.net/rochellecanale/xvdMz/

keep a counter
$(document).ready(function(){
var counter = 0;
$("[data-item]").on('click',function(){
$("#grid1 tbody").append("<tr><td><input type='text' value='123' style='width:100px' id='in-" + counter++ + "' /></td></tr>");
});
});
Demo: Fiddle

You can do it this way:
When you create a new row you can check for the current input's length and add that as a part of id.
$("[data-item]").on('click',function(){
var $el = $("<tr><td><input type='text' id='myInput" + ($('#grid1').find('input').length +1) + "' value='123' style='width:100px' id='' /></td></tr>");
$("#grid1 tbody").append($el);
});
Demo
I have another suggestion that instead of keeping the items to be cloned, you can go for templating, least you can put in your html itself like this.
<script type="text/html" id="clone">
<tr><td><input type='text' value='123' style='width:100px' id='' /></td></tr>
</script>
and then just use that to clone, this way you keep your html in one place and script in another.
$("[data-item]").on('click',function(){
var $el =$($.parseHTML($('#clone').html())).find('input').prop('id', "myInput" + ($('#grid1').find('input').length +1) ).end();
$("#grid1 tbody").append($el);
});
Demo

Related

Change name of input within specific table row

I'm using a function which I've adapted to clone table rows when a certain button is clicked (see this fiddle), and assign the new row an incremented ID (i.e. table-rows-1 to table-rows-2). After creating a new row, I want a function I'm making to find an input in a td in this row and change its name from input-text-1 to input-text-2. I'm not very confident with Javascript, and am having trouble accessing the input element within the row. Heres an example:
<table>
<tbody>
<tr class="modal-rows" id="table-rows-1">
<td>
<input type="text" class="input-text" name="input-text-1">
</td>
</tr>
<tr class="modal-rows" id="table-rows-2"> <<< DUPLICATED ROW WITH INCREMENT ID
<td>
<input type="text" class="input-text" name="input-text-1">
</td>
</tr>
</tbody>
</table>
How can I access the inner inputs of this table in order to change their name? Heres what I've tried:
var rowNum = document.getElementsByClassName("modal-rows").length
$('#table-rows-' + rowNum + ' .input-text').attr('name', 'input-text-' + rowNum);
$('#table-rows-' + rowNum).find('.input-text').attr('name', 'input-text-' + rowNum);
$('#table-rows-' + rowNum).children('.input-text').attr('name', 'input-text-' + rowNum);
Can anyone let me know where I'm going wrong?
You can use below code inside your duplicate function:
clone.children[0].setAttribute('name', 'input-text'+ ++i)

Trying to Add Row dynamically but getting error

I'm trying to add row consist of three textbox dynamically on click of button with id=btnASize and on click of button with id=btnASizeR want to add a row consist of four textboxes. and on click of button with id=btnWdDelete want to delete the last row which is generated with textboxes and so on.
The three buttons which is mentioned above are generated dynamically and rows with textboxes which will be generated below existing rows are also created on click of those dynamic buttons.Any idea would be appreciated Refer image
$("#btnASize").click(function () {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function insertRow(){}
function AddRow(SizeRange, Tolerancemin,Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl > thead> tr")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell = $(row.insertCell(-1));
cell.html(SizeR);
//Add TolMin cell.
cell = $(row.insertCell(-1));
cell.html(TolMin);
//Add TolMax cell.
cell = $(row.insertCell(-1));
cell.html(TolMax);
}
$("#btnWdDelete").click(function () {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type='button' ID='btnASize' value='AddSize' />
<input type='button' ID='btnASizeR' value='AddSizeRange' />
<input type='button' ID='btnWdDelete' value='Delete' />
<table ID='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'>
<input type='text' ID='SizeR' value='2.00' />
</td>
<td>
<input type='text' ID='TolMin' value='1' />
</td>
<td>
<input type='text' ID='TolMax' value='1' />
</td>
</tr>
</table>
</td>
</tr>
I prepared this sample to fulfill your requirement, although not a complete solution. You have to write some code by yourself. But this will give you a pretty good idea.
$('#btnAdd').click(function() {
var textboxSize = "<input class='form-control' type='text' class='size range'>";
var textboxTolerance = "<input class='form-control' type='text' class='tolerance'>";
var markup = "<tr><td>" + textboxSize + "</td><td>" + textboxTolerance + "</td></tr>";
$("#myTable tbody").append(markup);
});
$('#btnDelete').click(function() {
$("#myTable tbody>tr:last").remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<input class="btn-primary" id="btnAdd" type="button" value="Add Row">
<input class="btn-primary" id="btnDelete" type="button" value="Delete">
<table class="table" id="myTable">
<thead>
<th>
Size Range
</th>
<th>
Tolerance
</th>
</thead>
<tbody>
</tbody>
</table>
I think there are a few issues with your code.
You call insertRow on an HTMLTableRowElement. insertRow is a HTMLTableElement method, so we need to make sure we're calling it on a HTMLTableElement, instead of a HTMLTableRowElement. To fix this, we'll select the table. We can then use insertRow() on it.
You call $(row.insertCell(-1)) to insert a cell. This is invalid jQuery code. insertCell is a plain JS method for a HTMLTableRowElements, so we need to make sure we're calling it on the appropriate type of element. Specifically, we'll use row.insertCell(), instead of $(row.insertCell(-1)).
The Delete function contains similar errors, but I'll leave that one as is so you can learn by correcting it yourself.
$("#btnASize").click(function() {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function AddRow(SizeRange, Tolerancemin, Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell1 = row.insertCell(-1);
$(cell1).text(SizeRange);
//Add TolMin cell.
var cell2 = row.insertCell(-1);
$(cell2).text(Tolerancemin);
//Add TolMax cell.
var cell3 = row.insertCell(-1);
$(cell3).text(Tolerancemax);
}
$("#btnWdDelete").click(function() {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td><input type='button' ID='btnASize' value='AddSize' /><input type='button' ID='btnASizeR' value='AddSizeRange' /><input type='button' ID='btnWdDelete' value='Delete' />
<table id='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'><input type='text' ID='SizeR' value='2.00' /></td>
<td><input type='text' ID='TolMin' value='1' /></td>
<td><input type='text' ID='TolMax' value='1' /></td>
</tr>
</table>
</td>
</tr>

Alert multiple column using javascript

I'm trying to alert fields. Here is my html
<table width="100%" id="example1" class="table table-bordered table-striped">
<tr>
<td> Nip </td>
<td> Nama Lengkap </td>
</tr>
<tr id='ke0'>
<td> <input class="form-control nipnya" type="text" name="nip[]" /> </td>
<td> <input class="form-control namanya" type="text" name="namalengkap[]" /> </td>
</tr>
<tr id='ke1'>
</tr>
</table>
<div>
<a id="add_row" class="btn btn-success pull-left">Tambah Baris Baru</a>
<a id="delete_row" class="pull-left btn btn-danger">Hapus Baris</a>
</div>
and i have this jquery
$(document).ready(function() {
$("#rmnya").change(function() {
$('#td11').html($("#rmnya").val());
});
var i = 1;
$("#add_row").click(function() {
$('#ke' + i).html('<td><input class="form-control nipnya" type="text" name="nip[]" /> </td>' +
'<td> <input class="form-control namanya" type="text" name="namalengkap[]" />' +
'</td>');
$('#example1').append('<tr id="ke' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#ke" + (i - 1)).html('');
i--;
}
});
});
As you can see from my script. There is only one Row <tr></tr>. I can alert it if it only one row. But when click Tambah Baris Baru there is another row showing up. I can't alert it. Here is my other javascript
$(".nipnya").change(function(){
$('.nipnya').each(function(i, obj) {
alert($('.nipnya').val());
});
});
So, can you tell me how to alert after onchange in every field that showing up dynamically.
Here is my fiddle https://jsfiddle.net/spc5884w/
Sorry for my bad english.
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.
General Syntax
$(staticParentElement).on('event','selector',callback_function)
Example
$('table').on('click', ".nipnya", function(){
alert($(this).val());
});
DEMO

Get total from table input as grand total in jquery?

I created a simple stock saving table for my project. Also i added a button to add row to my table.this is my table,
[add button]
+---------------+-----------+-----------+
+ lense type + qty + total +
+---------------+-----------+-----------+
+ + + +
+---------------+-----------+-----------+
+ grand total : LKR +
+---------------------------------------+
EDIT
I added html code of the table,
<table class="table" id="tbl-add-lense">
<thead style="background-color:#f5edff;">
<th style="width:2%;"><input type="checkbox" name="chk_in" id="checkall"></input></th>
<th style="width:2%;">item no</th>
<th style="width:5%;">Lense Type</th>
<th style="width:5%;">Unit price</th>
<th style="width:5%;">Quantity</th>
<th style="width:5%;">Total</th>
</thead>
<tbody id="tbl-lesne-body">
<tr id="addr0">
<td><input type="checkbox" name="chk_in"></input></td>
<td>1</td> <td><input name='tb-lense-type1' type='text' placeholder='Lense Type' class='form-control '/> </td>
<td><input name='td-lunit1' type='number' placeholder='0' class='form-control'></td>
<td><input name='td-lqty1' type='number' placeholder='0' class='form-control'></td>
<td><input name='tb-ltotal1' type='number' placeholder='00.00' class='form-control total'></td>
</tr>
</tbody>
<tfooter></tfooter>
</table>
This table has one row. I used add button to add more rows. add row button code,
$("#add-lense-row").click(function(){
$("#tbl-lesne-body").append("<tr id='addr"+(i+1)+"'><td><input type='checkbox' name='chk_in'></input></td><td>"+ (i+1) +"</td> <td><input name='tb-lense-type"+i+"' type='text' placeholder='Lense Type' class='form-control '/> </td> <td><input name='td-lunit"+i+"' type='number' placeholder='0' class='form-control'></td><td><input name='td-lqty"+i+"' type='number' placeholder='0' class='form-control'></td><td class='tot'><input name='td-ltotal"+i+"' type='number' placeholder='00.00' class='form-control total'></td></tr>");
i++;
});
total <td> has a input ,
<input name='tb-ltotal1' type='number' placeholder='00.00' class='form-control total'>
I need to get sum of total td inputs when typing on a input. I tried this code,
$(".total").keyup(function(){
console.log('Typing');
sum += parseFloat($(this).val());
});
but it only working on the first table row. If i add a new row and try this code. It's not working. I removed sum += parseFloat($(this).val()); line and tried. Still code working only in the first row. How to solve this. Thank you
Your code needed some corrections:
You were only getting the value of input that triggered the 'keyup' event, as the sum. But you needed to loop through all inputs with class total and add the values of all to get the grand total.
As only the first row was added through html and rest of the rows were being added dynamically through javascript/jquery, your normal event binding worked only for the first row. For dynamically generated elements i.e. the elements which were not there when the page first loaded, you need to use slightly different syntax for event binding e.g. $(document).on("keyup", ".total", function(){}). By binding events dynamically in this way, keyup event now fires on all inputs.
$(document).on("keyup", ".total", function(){
console.log('Typing');
var sum = 0;
$(".total").each(function(index){
sum += parseFloat($(this).val());
});//each
console.log( sum );
});//keyup`

When a new row is added input name goes up by 1?

I'm using a button to add a row to my table.
I would like the input name on the 3 textboxes to go up by 1 when the row clones.
This is the script I'm using now. (it clones the row and adds it underneath, but it doesn't +1 the input name.
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #product').val('');
$('#mytable tbody>tr:last #qty').val('');
$('#mytable tbody>tr:last #remarks').val('');
$('#mytable tbody>tr:last #add').val('+');
return false;
});
});
This is my Table
<table id="mytable" width="250px" border="0" cellspacing="0" cellpadding="0" style="text-align:center; padding-left:40px; padding-bottom:8px">
<tr class="product">
<td style="text-align:center;"><strong>Item</strong></td>
<td style="text-align:center;"><strong>Qty.</strong></td>
<td style="text-align:center;"><strong>Remarks</strong></td>
</tr>
<tr name="product" class="product">
<td width="100px"><input type="text" width="100px" name="product" id="product" /></td>
<td width="5px" style="text-align:center; padding-left:2px; padding-right:2px;"><input type="text" width="5px" size="1" maxlength="2" name="qty" id="qty" /></td>
<td width="100px"><input type="text" width="100px" name="remarks" id="remarks" /></td>
<td><input type="submit" name="add" id="add" value="+" /></td>
</tr>
</table>
The question is: How would I have the input names "product" "qty" "remarks" change to "product1" "qty1" "remarks1" on the next row? And 2 on the row after 3 on row after that to infinite amount of rows.
Thank you for taking a look.
The following seems to work, added to your click() handler:
$('#mytable tbody > tr:last input').each(
function(){
/* the following removes the numerical characters from the id */
var id = this.id.replace(/[0-9]+/g,'');
/* this iterates through each id that starts with the same sequence
of characters */
$('input[id^=' + id + ']').each(
function(i){
/* this sets the id to the sequence of characters,
plus the number of the current iteration of the
each() method */
this.id = id + i;
});
});
JS Fiddle demo.
Edited in response to comment from the OP (below):
...But the id goes up by 1 I need the input name to go up by 1. How would I change this to increase"name"?
You can do that easily enough, just make the name equal to the id in the inner each() call:
$('#mytable tbody > tr:last input').each(
function(){
/* the following removes the numerical characters from the id */
var id = this.id.replace(/[0-9]+/g,'');
/* this iterates through each id that starts with the same sequence
of characters */
$('input[id^=' + id + ']').each(
function(i){
/* this sets the id to the sequence of characters,
plus the number of the current iteration of the
each() method */
this.id = id + i;
this.name = this.id;
});
});
http://jsfiddle.net/davidThomas/WMvRJ/4/
References:
attribute starts-with selector: ^=.
each().
RegExp, at the Mozilla Developer Network.
replace(), at the Mozilla Developer Network.
You could either have a global variable in javascript keep track of the row number, or you could use javascript to parse the previous row's number. I would personally use a global variable.

Categories

Resources