Dynamically creating id's

2

I'm currently creating the element this way:

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

My JS, looks like this:

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

I'm currently running an alert to test. But it is only working in the first input, and in the second, it does not work. Could someone guide me how should I proceed?

    
asked by anonymous 02.03.2015 / 19:25

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 it 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"/>';

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

    
02.03.2015 / 19:51
1

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

If you want a list, you must use the class selector .

Example:

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

$('.link').click(function(){
    console.log(this);
});
    
02.03.2015 / 19:30