Reputation: 7520
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/
Upvotes: 0
Views: 2381
Reputation: 123739
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);
});
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);
});
Upvotes: 1
Reputation: 388316
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
Upvotes: 2