I have 'for loop' and I want to send the values through jquery but I can't increment the value of id, 'my_id' is the id of my input fields.
for(i=0;i<6;i++){
$("#my_id_+i").val('test');
}
I have 'for loop' and I want to send the values through jquery but I can't increment the value of id, 'my_id' is the id of my input fields.
for(i=0;i<6;i++){
$("#my_id_+i").val('test');
}
Share
Improve this question
edited Sep 18, 2019 at 12:05
Clarity
10.9k2 gold badges27 silver badges38 bronze badges
asked Sep 18, 2019 at 12:01
Soft TechnoesSoft Technoes
1,1151 gold badge10 silver badges19 bronze badges
3
-
2
$("#my_id_" + i).val('test');
– XCS Commented Sep 18, 2019 at 12:02 - 1 @Soft Technoes, It's always better if you post entire blocks related to the question. In your case that would be the DOM section that you want to update and js part. In that way you can get better answer. For instance, if your code like <div id='my_id_1'></div><div id='my_id_2'></div><div id='my_id_3'></div>. The easiest way to update them all would be to add a single class across all divs, so you can update their value with one line of code. $(".classname").val("test"). But if you have n number of divs, probably for loop is the way to go. – Nesar Commented Sep 18, 2019 at 12:14
- If you have for loop and you're using jQuery. Why not use the jquery.each like the following: $('[id*="my_id_"]').each(function(indx){ // your code console.log($(this)); // to set a value $(this).val('test'); }) – Rayan Commented Sep 18, 2019 at 12:19
8 Answers
Reset to default 3With ES6 you can use let
to properly scope variable to the loop and string interpolation to make the code cleaner:
for (let i = 0; i < 6; i++) {
$(`#my_id_${i}`).val('test');
}
i
has dynamic value but your code treat that as a string.
Try
$("#my_id_"+i).val('test');
you are putting i
inside double quote hence it is part of string and not getting evaluated as variable. keep it outside and it will work
for(i=0;i<6;i++){
$("#my_id_" +i).val('test');
}
Just put the +i outside of the String
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}
for this purpose you can bine string with i
that you get from for each loop:
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}
$("#my_id_+i").val('test'); and maybe it would be better to declare the counter with let declaration
for(let i = 0; i < 6; i++){
$("#my_id_" + i).val('test');
}
You can use a template string to reference a variable from within a string literal:
for(i = 0; i < 6; i++){
$(`#my_id_${i}`).val('test');
}
You can also use +
but with the + i
out of the string literal:
for(i = 0; i < 6; i++){
$("#my_id_" + i).val('test');
}
If you don't have more 6
elements whose id
starts with my_id_
, you can avoid a loop and use:
$('[id^="my_id_"]').val('test');
Thanks I found the solution. This part is working fine..
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}