$(document).ready(function() {
for (i=1;i<= 12;i++) {
$(".panel" + i).click(function() {
$("#panel").val($(".for-panel" + i).text());
});
}
});
This code is not working.
Where is the problem from?
$(document).ready(function() {
for (i=1;i<= 12;i++) {
$(".panel" + i).click(function() {
$("#panel").val($(".for-panel" + i).text());
});
}
});
This code is not working.
Where is the problem from?
Here the for loop runs first and updates the value of i
to 13 when it's execution is over. But the function inside $(".panel" + i).click()
will trigger only after clicking the button. At that time the value of i
will be 13.
You can avoid this situation by using jquery data-
attribute.
HTML
<button class="panel" data-id="1">Panel1</button>
<button class="panel" data-id="2">Panel2</button>
<button class="panel" data-id="3">Panel3</button>
.
.
<button class="panel" data-id="13">Panel13</button>
Jquery
$(document).ready(function() {
$(".panel").click(function() {
var i = $(this).data('id');
$("#panel").val($(".for-panel" + i).text());
});
});
For reference : https://api.jquery.com/data/