0

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, thank you! That is what I was looking for exactly!
@AndrewZ glad to help!
0

This will work in your case

 var brInput = document.createElement("br");
    brInput.setAttribute("id", "uniqueIdentifier");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.