san A
san A

Reputation: 177

Can we set attribute 'id' to different 'buttons' via loop using javascript or jquery?

I want to achieve the following:

Let say I have ten buttons on my page, and they all are dynamically generated. I have added ID to all of these ten buttons, say id be 1,2,3....10. using the following code.

function createButton(id){
       button.setAttribute("name", id);
}

Now I want to add 'onlick' event to all these button, like this

function abc()
      $(document).on('click','#1', function(){
      callSomeFunc();
});

This way I'll have to write the above code 10 times with different Id's. I tried to use loop over the function as

function abc()
   for(var i=1, i<=10, i++){
          $(document).on('click',id, function(){
          callSomeFunc(id);
   });
}

to no avail ! How can I achieve this ?

Upvotes: 1

Views: 1458

Answers (2)

Derek Story
Derek Story

Reputation: 9593

There is no need to wrap your click event in a function. You can simply have it listening for a click event. And since each id is calling the same function, you can generalize it by a className rather than the specific ID:

 $(document).on('click', 'div', function() {
   callSomeFunc();
 });

Codepen Example

And to get the id value, you can use this.id:

 $(document).on('click', 'div', function() {
    callSomeFunc(this.id)
 });

ID Example

Upvotes: 2

ChrisM
ChrisM

Reputation: 1673

The immediate fix for your function, sticking to the way you are trying to do it, is to do the following:

function abc()
   for(var i=1, i<=10, i++){
          $(document).on('click','#' + i, function(){
          id = $(this).prop('id');
          callSomeFunc(id);
   });
}

Note I've added '#' explicitly and am referring to your index counter not 'id' in the intial selector.

I would recommend some refinements, however. You can always avoid the $(document) clunkiness:

function abc()
   for(var i=1, i<=10, i++){
          $('#' + i).click(function(){
          id = $(this).prop('id');
          callSomeFunc(id);
   });
}

Further is there a reason you are using ID's? If you set up a common class you could do this all in one fell swoop! Plus if you are using id to give different behaviour for different buttons, you could just do that within the event handler using $(this)

//This will apply the click handler to every element that has class="someClass"
$('.someClass').click(function(){
        //Do stuff with $($this)
});

Upvotes: 1

Related Questions