Get items with similar id using jQuery

I have div boxes with addresses, each address has its own button, the button should open a dialog in which you can edit a specific address.

Button identifiers are always edit_address_ (number), and number is the database identifier. Thus, the numbers are not like 1,2,3, but can be 12, 35, 122, the dialog boxes for display have the identifier dialog-form_ (number).

So, how can you implement something, first get all the finite numbers of existing identifiers, and then make a 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 that this code does not work correctly, but how to implement it?

+4
source share
3 answers

Since the identifier is dynamically generated, it is much easier for it to add a common class name to all controls, such as "edit_address", and the selector is simply the class name. Adding another simple data attribute for a unique identifier that needs to be used as a numeric identifier, then minimizes the 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'); }) 
+4
source

For each element whose id begins with "edit_address_", attach a click event that will open the corresponding dialog, retrieving the actual identifier of the database you are 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 original selector with a tag to make it faster. For example: "input[id^='edit_address_']" or "button[id^='edit_address_']"

+7
source

Use jQuery 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'); }); 

The following is a brief description of the attribute selector statements:

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

Source: https://habr.com/ru/post/1399228/


All Articles