Reputation: 16946
Using dot.js I'm adding a button to a specific web page that, when clicked, should add some text to a text field and then trigger another button to also be clicked. I simulate this by adding a click handler to my button which has this code:
var button = $('.some-class').find('button')[0];
console.log(button); // element I expect
button.click();
However, this doesn't work and I'm not sure why. If instead of .click()
I perform .remove()
, the button is removed from the page. If I use the console to execute the same code, the button does get clicked. This tells me I do have the right element, but there is something wrong with the click()
event specifically.
Can someone explain why this isn't working in either Safari or Chrome? I've tried a lot of different things, but I'm new to jQuery so I'm probably missing some detail in how that works.
Upvotes: 0
Views: 100
Reputation: 8423
We went to the bottom of this in the chat. What probably caused the problem was another event-handler attached to (possibly) body, that undid the click.
So the solution was to stop the event
from propagating:
event.stopPropagation();
Upvotes: 1
Reputation: 32354
try jquery's trigger()
function:
$(button).trigger('click');
see jsfiddle: https://jsfiddle.net/665hjqwk/
Upvotes: 0
Reputation: 1
You can use the following statement.
var button = $('.some-class').find('button')[0].trigger('click');
Upvotes: 0
Reputation: 1
The problem is the click() function is from jquery and you're attempting to fire the click function from the DOM object.
Try
$(button).click();
Here's a plunk. http://plnkr.co/edit/2pcgVt
Upvotes: 0
Reputation: 68393
While assigning the click event handler to the button you should use jquery on This should ensure that whenever a new button with added with same selector (as in when event was assigned), event handled will be assigned to that button
Some examples here
Upvotes: 0