0

So I have an array of buttons and when I try to assign for each one a click event like this button[i].bind("click", function() ... it says the Object # has no method "bind".

What can be the problem ?

2
  • Could you post a small snippet of the code? You may not need to iterate over an array. Commented Dec 27, 2013 at 11:05
  • You can try this stackoverflow.com/questions/13883225/… Commented Dec 27, 2013 at 11:08

5 Answers 5

1

you should try

$(button[i]).on("click", function(){});

button[i] is a javascript object so you need to convert it in jQuery object by using $(button[i]) to apply jquery events.

Sign up to request clarification or add additional context in comments.

Comments

1

button[i] isn't a jquery object, so it doesn't have bind function.

You're not showing enough code for me to give you the full solution but you should end up with

$(button[i]).bind("click", function(){}); 

Comments

0

The array "button" probably contains selectors (strings like "#xyz"), not objects. You need to convert them to objects:

$(button[i]).bind("click", function()

Comments

0

Given the following HTML:

<button>Something</button>
<button>Something</button>
<button>Something</button>

You can obtain the array of buttons as follows:

var buttons = document.getElementsByTagName("button");

Then just pass the entire array to jQuery to bind the buttons:

$(buttons).click(function(){
   alert("hello");
});

Or just select all the buttons to start with:

$("button").click(function(){
   alert("hello");
});

The main point I'm trying to convey is that you most likely do not need to iterate over the button [] with .forEach.

Comments

0

if these buttons exist within a common ancestor it would be more performant to bind the click on that parent element.

$('.parent').on('click','button',function(e){
   ...
});

If these buttons have a common function then that makes life easier - if there is are different behaviours required for each function then look to use a data attribut on the button where you could specify a different method to execute for each.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.