Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get elements with similar ID's using jQuery

I've got div-boxes with addresses, each address has its own button, the button should open up a dialog in which you can edit the certain address.

The buttons ID's are always edit_address_(number), and the number is an ID of the database. So the numbers aren't like 1,2,3 but could be 12, 35, 122, the dialogboxes to show up have the ids dialog-form_(number).

So how can realise something first get all the ending numbers of the existing IDs and then make the loop for it

$( "#dialog-form_$i" ).dialog({
    autoOpen: false,
    height: 300,
    width: 390,
    modal: true
    });

$('#edit_address_$i').button().click(function() {
    $('#dialog-form_$i').dialog('open');
}); 

I know this code doesn't work that way, but how to realise it?

like image 868
sinini Avatar asked Dec 06 '22 16:12

sinini


1 Answers

For each element whose id starts with "edit_address_", bind a click event that will open the corresponding dialog by extracting the actual database ID you're talking about.

$("[id^='edit_address_']").click(function() {
    var id = this.id.split('_')[2];
    $('#dialog-form_' + id).dialog('open');
}).button();

Note: depending on the type of element, you can prefix the initial selector with the tagname so it will be faster. For instance: "input[id^='edit_address_']" or "button[id^='edit_address_']"

  • jQuery selectors
  • .click()
like image 71
Didier Ghys Avatar answered Dec 10 '22 11:12

Didier Ghys