0

I have a page with a search button on it.

in my Javascript i have a click event that looks like this:

if(blah){
  $('#search').click();
}

$('#search').on('click', function(){
  // Do something
});

What would be the reason the if statement wouldn't click the button to cause the onclick to fire?

All of this is wrapped in an onReady as well.

The html on the page is a standard button:

<button id='search' type="button" class="btn btn-primary">Search RefID</button>
5
  • 1
    if blah evals to a false... triggering a click will also only run the defined click handler, not the native functionality Commented Oct 2, 2014 at 18:35
  • It doesn't, I put an alert before and after the .click() so I know it gets there Commented Oct 2, 2014 at 18:35
  • 5
    You seem to bind the handler after you triggered the click. The handler is not executed because it does not exist (at that moment). Commented Oct 2, 2014 at 18:36
  • @FelixKling that was it :( my mistake Commented Oct 2, 2014 at 18:37
  • @FelixKling I think you should turn your comment into an answer. Commented Oct 2, 2014 at 18:39

1 Answer 1

3

You seem to bind the handler after you triggered the click. The handler is not executed because it does not exist (at that moment).

Put the if-clause after the click-handler and it works:

http://jsfiddle.net/kksgj4xL/

var blah = true;

$('#search').click(function(){
  alert("poep");
});

if(blah){
  $('#search').click();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.