Reputation: 1105
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');
}
Upvotes: 0
Views: 2899
Reputation: 1105
Thanks I found the solution. This part is working fine..
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}
Upvotes: 0
Reputation: 22766
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');
Upvotes: 1
Reputation: 339
$("#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');
}
Upvotes: 1
Reputation: 68933
i
has dynamic value but your code treat that as a string.
Try
$("#my_id_"+i).val('test');
Upvotes: 2
Reputation: 10873
With 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');
}
Upvotes: 3
Reputation: 1403
for this purpose you can combine string with i
that you get from for each loop:
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}
Upvotes: 1
Reputation: 281
Just put the +i outside of the String
for(i=0;i<6;i++){
$("#my_id_"+i).val('test');
}
Upvotes: 1
Reputation: 28513
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');
}
Upvotes: 1