Create id’s dynamically

Asked

Viewed 59 times

2

I am currently creating the element in this way:

$ss = '<input id="link" class="link[]" title="SS" type="image" src="../cancel.png"/>';

My JS, is that way:

$("#link").click(function(){
        alert("SIM");
});

At the moment I am running an Alert to test. But it is only working in the first input, already in the second, it does not work. Someone could guide me as I should proceed?

2 answers

2


Ids must be unique, use classes instead of Ids.

If you want to use Ids you have to differentiate them. Using classes is simpler:

$("[class='link[]']").click(function(){
        alert("SIM");
});

or only

$(".link").click(function(){
        alert("SIM");
});

if in HTML you have '<input class="link" ...

If you really want to use Ids generates different numbers for example when creating these links:

var input= 0;
// e depois cada novo input:
$ss = '<input id="link' + (input++) + '" class="link[]" title="SS" type="image" src="../cancel.png"/>';

and then you use $([id^=link]) as jQuery selector. Note that if these elements are generated dynamically you may need to delegate the event.

  • Sergio, '$(". link"). click(Function(){' did not work, only with '$("[class='link[]']). click(Function(){'. Thanks

  • @Exact felipefm, as I said in the reply uses $(".link") if in HTML you have '<input class="link" ...

  • I understood, and to get your value, would be the same reasoning? Would have to pick up via class too?

  • @Felipefm inside this function you can use native: this.value or with jQuery $(this).val();

  • Perfect Sergio! Thanks for your help!

1

This happens because the id selector jQuery internally uses document.getElementById, thus returning the first and/or single element corresponds to such id.

If you want a list, you have to use the class selector.

Example:

$ss = '<input class="link" class="link[]" title="SS" type="image" src="../cancel.png"/>';

$('.link').click(function(){
    console.log(this);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.