Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through all tags having different ids in jquery?

I want to iterate through my django formset which has ids using jquery.

id="id_lines-0-label"
id="id_lines-0-description"
id="id_lines-1-label" 
id="id_lines-1-description"
id="id_lines-2-label"
id="id_lines-2-description"
id="id_lines-3-label"
id="id_lines-3-description
# and so on.

There is an add button which adds forms to formset. so it should only iterate though the forms that are added.

I have updated my question. My html has field label and description which has ids as shown above and i want to select only the field which has label in its id.

like image 516
Mike Pinkman Avatar asked Oct 29 '22 15:10

Mike Pinkman


1 Answers

You can use the substring selector to get all the elements with a given substring. For an example lets say we have a div with those id then you can use div[id*='id_lines-'] selector to get all the elements with that pattern:

$(document).ready(function(){
  $( "div[id*='id_lines-']" ).each(function(index){
    var id = $(this).attr('id');
    //select only label with id that has label text in its id
    if(id.indexOf('-label') !== -1){
      $(this).html('This is selected label id = '+id);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="#id_lines-0-label"></div>
<div id="#id_lines-0-description"></div>
<div id="#id_lines-2-label"></div>
<div id="#id_lines-3-description"></div>
<div id="#id_lines-3-label"></div>
<div id="#id_lines-3-description"></div>
<div id="#id_lines-3-label"></div>
like image 58
Ankit Agarwal Avatar answered Nov 16 '22 15:11

Ankit Agarwal