I’m trying to call many button by one jquery function. following is my html and php code:
Elements of button:
for($q_no=1;$q_no<=30;$q_no++){
echo('<button class="q_no_btn" id="'.$q_no.'">Question no '.$q_no.'</button>');
}
My Jquery code:
$(document).ready(function(){
var q_no;
for(q_no=1;q_no<=30;q_no++){
$("#"(q_no).click(function(){
alert("Click on 1!!!");
}))
}
});
I’m poping up the content to popup box, by clicking on the buttons.
please help.
2
Answers
You have misspelled when calling your id parameter with jQuery.
If you change the $("#"(q_no) field as below, the problem will be solved. Also, you wrote one extra bracket.
Also you can use below code, you no need to use loop in jquery.
loop
We are using the fact that
let
is used for defining block-scoped variables to our advantage. We create aq_no
variable usinglet
in ourfor
and define theclick
function inside this block, so each handler will have its own, correctq_no
.loop is not even needed
In Javascript, indexing starts from 0, so we add 1 to it.
Without jQuery