-3

I'm trying to trigger a click on an input field on page load. The input field is placed within a form.

HTML:

<form>
.... other fieldsets ....
<fieldset>
<ul class="chosen-choices">
<li class="search-field">
<input class="default" type="text" style="width: 147px;" autocomplete="off" value="Choose a category…">
</li>
</ul>
</fieldset>
.... other fieldsets ....
</form>

jQuery

<script>     
    $('.default').trigger('click',function() {
            console.log( '.trigger() called.');
        });
    console.log('done');        
</script>

The jQuery trigger is not run, as nothing appears in console, besides the 'done' log.

I want to trigger a click on the input field with class "default".

Troels Johannesen
  • 725
  • 2
  • 7
  • 30

3 Answers3

2

Apart from the problem, that your code does not bind a click-event to the input element in question you have not made sure that the action happens after the page is fully loaded.

Place your code into the onload-section ($(function(){...})) and also bind a function for the click-event ($('.default').bind(function(){...}); and it will work. The appended .click() (without an argument) is actually a short form of .trigger('click') and does exactly the same, see here (make sure to open the console to see the output generated):

$(function(){ // anything in this function gets executed *after* the DOM has finished loading
  $('.default').click(function() {
     console.log( '.trigger() called.');
   }).click(); // same as: .trigger('click');
      console.log('done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="chosen-choices">
<li class="search-field">
<input class="default" type="text" style="width: 147px;" autocomplete="off" value="Choose a category…">
</li>
</ul>

This solution works without explicitely using trigger(), but it triggers the click-event that was previously bound to the DOM element by calling .click() without an argument.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

Ensure the jquery code is put last in the page just before see here

Or you can use the defer="defer" tag if this helps with your formatting (please not that firefox doesn't support the defer attribute

Community
  • 1
  • 1
Parsa
  • 3,054
  • 3
  • 19
  • 35
0

.trigger() triggers the click. It doesn't handle the event that's fired. You need to have an event handler for that.

@cars10's code neatly does both. I'd add this as a comment to that answer but I don't have enough rep yet.

Dave Thomas
  • 425
  • 2
  • 10