user3736335 user3736335 - 6 months ago 10
HTML Question

Setting Unique ID's of form elements on dynamic creation

I am making a script to add a row dynamically. I am using the below function for it. The problem however is that it does creates the new row, but doesn't assigns unique ID's to the elements.

Javascript:

$(document).ready(function () {
var counter = 1;
$("#add_row").click(function () {
var row_id = "row" + counter;
console.log(row_id);
new_elem = $("#new_row").clone().appendTo("#table_invoice tbody").show().attr("id", row_id);
var button_id = "button" + row_id;
var input_id = "row" + row_id;
document.getElementById('row_id').firstChild.setAttribute('id',input_id);
document.getElementById('row_id').firstChild.nextSibling.setAttribute('id',button_id);
console.log(button_id);
console.log(input_id);
counter += 1;
});
});


HTML:

<table class="table table-striped" id="table_invoice">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<tr id ="new_row" style="display:none;">
<th><input type="text" class="form-control" placeholder="Enter Product ID" /></th>
<th><button type="button" class="btn btn-default"">Add Product</button></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
<a id="add_row" class="btn bt-default">Add New Row</a>


Also, I get the following error:


TypeError: document.getElementById(...).firstChild.setAttribute is not a function


Can't figure out why this is not a valid function.

Answer

using jQuery this is how you do it: DEMO

note that I've changed all the row_ids to counter, 'cause I think that is the intended approach.

$(document).ready(function () {
        var counter = 1;
        $("#add_row").click(function () {
            var row_id = "row" + counter;
            console.log(row_id);
            new_elem = $("#new_row").clone().appendTo("#table_invoice tbody").show().attr("id", row_id);
            var button_id = "button" + counter;
            var input_id = "input" + counter; //I think you meant "input" because if you set "row" at the beginning it would be duplicated of the tr
            $('#'+row_id).find('button').attr('id',button_id);
            $('#'+row_id).find('input').attr('id',input_id);
            console.log(button_id);
            console.log(input_id);
            counter++;
        });
    });