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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With