Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Jquery, I want to bind some buttons in a loop but failed?

I can alert each button’s id by doing so.

$(function () {
  bind_button();
});
function bind_button() {
  var len = $(".btn-sm").length;
  for(var i = 0; i < len; i ++ ){
    alert($(".btn-sm")[i].id);
  }
}

But when I want to bind the button with its id…

$(function () {
  bind_button();
});
function bind_button() {
  var len = $(".btn-sm").length;
  for(var i = 0; i < len; i ++ ){
    $(".btn-sm")[i].click(function (){
      alert($(".btn-sm")[i].id);
    });
  }
}

When I click the button, no alert appears.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Anyone knows why? And anyone knows how can I bind successfully?

>Solution :

If you want to print only the id of the clicked button just do something like

function bind_button() {
   $(".btn-sm").click(function(){
      alert(this.id);
   });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading