jQuery .submit() trigger problem

Recently I experience the following problem, when I call this code it triggers an error in FireBug:

$('input[name="s"]').parents('form').submit();

With “human” words: I trired to find a input with a spefic name, then find the form wrapping this input and try to submit it. Strangely, but it trows an error in jQuery lib.

The form has the following structure:

<form method="get" id="searchform" action="http://localhost/wordpress/">
   <label for="s" class="assistive-text">Search</label>
   <input type="text" class="field" name="s" id="s" placeholder="Search" />
   <input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" />
</form>

Probably some of you will notice that this is search form from WordPress.

I searched in internet and found that there are similar issues in the jQuery bug tracker, but they are closed with “wontfix” message explaining that this is a Dom problem.

Here is the working example of the problem: click. Click on the submit button in the first form and it will do what is shold do, but button “not working” will trigger the error.

Ok, now the solution – find the button submit and trigger a click. Click on the button “working” in the first form in the example and you will see that it will submit properly the value.

Here is the solution:

$('input[name="s"]').parents('form').find('input[type="submit"]').trigger('click');
//or if you know the position of the submit button
$('input[name="s"]').next().trigger('click');

The second form doesn’t have input with name or id “submit” and the normal submit() function is triggered correctly.

That’s it. Enjoy!

4 thoughts on “jQuery .submit() trigger problem

  1. Nik ChankovNo Gravatar Post author

    You are right. In my day-to-day work I didn’t use even names for these butons, but this particular case I need to make it work for all cases. The reason is that I did this for my WordPress plugin Autocompleter and I cannot guarantee what theme is used and if this button is renamed. That’s why this solution should cover most of the cases.

  2. AnkitNo Gravatar

    You could also have changed “name” attribute of the Submit button.
    E.g.
    <input type=”submit” class=”submit” name=”submit” id=”searchsubmit” value=”Search” />

Leave a Reply

Your email address will not be published. Required fields are marked *