user2612488
user2612488

Reputation: 11

Dynamically created form fields keep having the same ID

I dynamically add some text fields to my page with this line of code:

var textboxCount = 0;

$('#addFields').on('click', function(){

var TextField = document.createElement("input");

TextField.setAttribute("type", "text");
TextField.setAttribute("value", textboxCount);
TextField.setAttribute("name", "textbox");
TextField.setAttribute("class", "foo");
TextField.setAttribute("id", "textbox" + textboxCount);
TextField.setAttribute('onkeyup','doSomething('+textboxCount+');'); // for FF
TextField.onkeyup = function() {doSomething(textboxCount);}; // for IE

jQuery('#TextfieldList').append(eleText);
textboxCount += 1; //Increment the count

});

Now I need the unique ID of the field in this function:

function doSomething(id){
    alert(id);
}

But when I call the function, I keep getting the same ID with every added field. The value in the textfield is correct though.

Upvotes: 1

Views: 194

Answers (3)

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

You could just use the jQuery library you have in play:

$('#addFields').on('click', function () {
    var thisId = $('.foo').length + 1;
    var TextField = '<input type="text" name="textbox" class="foo" value="' + thisId + '" id="textbox' + thisId + '">';
    jQuery(TextField).appendTo('#TextfieldList');
});
$('#TextfieldList').on('keyup', '.foo', function () {
    doSomething($(this).attr('id'));
    // or 
    doSomething(this.id);
});
function doSomething(id){
    alert(id);
}

Sample jsFiddle: http://jsfiddle.net/mHT7Z/

Upvotes: 0

Musa
Musa

Reputation: 97672

Since you want to get the id of an element in its own event handler you can bypass the whole closure issue by just referencing this.id, where this is the element and id is its id property

TextField.onkeyup = function() {doSomething(this.id);};

Upvotes: 2

Pointy
Pointy

Reputation: 413720

Extremely common problem. Change the keyup handler:

TextField.onkeyup = function(textboxCount) {
  return function() {
    doSomething(textboxCount);}; // for IE
  };
}(textboxCount);

(Get rid of the "For FF" line; it's not necessary at all.)

If you don't introduce a new lexical scope somehow, then all of your event handlers will be referring to the exact same "textboxCount" variable. By doing something like what I've shown above (and there are variations), you ensure that each event handler has its own private copy of the counter as it stood at the time the handler was created.

Upvotes: 2

Related Questions