Home > Blockchain >  How to Click many buttons by jquery for loop
How to Click many buttons by jquery for loop

Time:01-03

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  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.

CodePudding user response:

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.

$(document).ready(function(){
    var q_no;
    for(q_no=1;q_no<=30;q_no  ){
        $("#" q_no).click(function(){
            alert("Click on 1!!!");
        });
    }
});

Also you can use below code, you no need to use loop in jquery.

$(".q_no_btn").on('click',function(){
    var ids = $(this).attr("id");
    alert("Click on "  ids  "!!!");
});

CodePudding user response:

loop

We are using the fact that let is used for defining block-scoped variables to our advantage. We create a q_no variable using let in our for and define the click function inside this block, so each handler will have its own, correct q_no.

let buttons = "";
for (let q_no = 1; q_no <= 30; q_no  ) {
    buttons  = '<button  id="'   q_no   '">Question no '   q_no   '</button>';
}

document.body.innerHTML = buttons;

for (let q_no = 1; q_no <= 30; q_no  ) {
    $("#"   q_no).click(function() {
        alert("Click on "   q_no);
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

loop is not even needed

let buttons = "";
for (let q_no = 1; q_no <= 30; q_no  ) {
    buttons  = '<button  id="'   q_no   '">Question no '   q_no   '</button>';
}

document.body.innerHTML = buttons;

$(".q_no_btn").click(function(obj, index) {
    console.log(1   $(this).index());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In Javascript, indexing starts from 0, so we add 1 to it.

Without jQuery

    let buttons = "";
    for (let q_no = 1; q_no <= 30; q_no  ) {
        buttons  = '<button  id="'   q_no   '">Question no '   q_no   '</button>';
    }

    document.body.innerHTML = buttons;
    
    let items = [...document.getElementsByClassName("q_no_btn")];
    
    for (let item of items) {
        item.addEventListener("click", function() {
            alert(items.indexOf(item)   1);
        });
    }

  • Related