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?

Answers:

Answer

Since ID's are being dynamically generated, it's sure a lot simpler to add a common class name to all the controls like "edit_address" then the selector is simply the class name. Adding another simple data-attribute for a unique identifier you need to use like a numeric ID then minimizes need to parse attributes

<button id="edit_address_$i" class="edit_address" data-id="$i">Text</button>

$('.edit_address').click(function(){
    $('#dialog-form_' + $(this).data('id') ).dialog('open');
})
Answer

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_']"

Answer

Use jQuery's attribute selector:

$("input[id^='edit_address_']????????????????").each(function() {
    $( "#" + this.id ).dialog({
         autoOpen: false,
         height: 300,
         width: 390,
         modal: true
    });
});

$("input[id^='edit_address_']????????????????").click(function() {
    $('#dialog-form_$i').dialog('open');
}); 

Here's a quick rundown of the attribute selector operators:

=  is exactly equal
!= is not equal
^= starts with
$= ends with
*= contains

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.