Andrew Z Andrew Z - 1 month ago 7
C# Question

How to add unique id's to dynamically added controls(Asp.net MVC)

I'm pretty new to Javascript, and I was wondering how to add unique id's to my generated HTML textboxes. I'm currently using this script to create textboxes:

$(document).ready(function () {
var tbId = 'expense';
var chkId = 'Mastercard';


$("#txt").click(function () {

var br = document.createElement("br");
var ctrl = $('<input/>').attr({ type: 'text', name: 'text', value: 'Indskriv udgift', id: tbId }).addClass("form-control tb_Id");
var ctrl2 = $('<input/>').attr({ type: 'checkbox', name: 'chk', id: chkId }).addClass("chk chk_Id");
$("#ExpenseBoxes").append(br, ctrl, 'Mastercard: ', ctrl2, br);
});


});


And this is the HTML code to add and hold the textboxes:

<input type="button" id="txt" value="Add TextBox"/>
<div id="ExpenseBoxes">
</div>


I want the textbox id's to be named "expense1, expense2, expense3 ~" but I'm not sure how to go about it.

Answer

What about using a counter ?

$(document).ready(function () {
  var tbId = 'expense';
  var chkId = 'Mastercard';
  var elementCounter = 0;


  $("#txt").click(function () {
    var br = document.createElement("br");
    var ctrl = $('<input/>').attr({ type: 'text', name: 'text', value: 'Indskriv udgift', id: tbId + (++elementCounter) }).addClass("form-control tb_Id");
    var ctrl2 = $('<input/>').attr({ type: 'checkbox', name: 'chk', id: chkId }).addClass("chk chk_Id");
    $("#ExpenseBoxes").append(br, ctrl, 'Mastercard: ', ctrl2, br);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="txt" value="Add TextBox"/>

<div id="ExpenseBoxes">
</div>

Just create this var elementCounter = 0;, concat it like id: tbId + (++elementCounter) and you will get incremental ids "expense1", "expense2", "expense3" and so on.

Comments