1

How would I submit a form when the user clicks an option using jQuery? I found one similar question using the datepicker text input but I'm not that familiar with jQuery so I can't seem to convert it to work for a select item.

Emsu
  • 203
  • 2
  • 4
  • 13

6 Answers6

8

On click of an <option>:

$('option').click(function ()
{
    $(this).closest('form').submit();
});

On change of a <select> (this is probably the one you want):

$('select').change(function ()
{
    $(this).closest('form').submit();
});

As @Guffa commented:

The click event on options doesn't work in all browsers. Safari for example does't trigger it.

...so you definitely want the second one.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    Upvoted, but recommend double-checking that the click event fires when the user selects an option via the keyboard as well. You might need to use the change event on the select instead of the click event on the option. – RwwL May 25 '11 at 21:49
  • The `click` event on options doesn't work in all browsers. Safari for example does't trigger it. – Guffa May 25 '11 at 21:55
3

The click event on options doesn't work in all browsers. Use the change event of the select element.

Example:

$('select').change(function(){
  this.form.submit();
});

Note that the submit event of the form is not triggered when you call the submit method to post the form.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

A small correction of these answers:

$(document).ready(function() {
    $('#some_link').click(function() {
        $('#form_id').submit();
    });
});
BenjaminRH
  • 11,974
  • 7
  • 49
  • 76
Igor
  • 2,834
  • 2
  • 26
  • 44
0
$('#option').click(function () {
    // form validation and such then

    $('form').submit();
})

This is the easiest way i can think of

UPDATE:

for specific form, you can use its name or id, it really depends on how your html looks like

$('form[name="formnamehere"]').submit();
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • What if there is more than one form on the page? – Matt Ball May 25 '11 at 21:52
  • ...or you can see [@Guffa's answer](http://stackoverflow.com/questions/6131346/jquery-submit-form-for-select-option-onclick/6131408#6131408) or [my answer](http://stackoverflow.com/questions/6131346/jquery-submit-form-for-select-option-onclick/6131386#6131386). – Matt Ball May 25 '11 at 22:02
0
$('select').change(function() {
  $('form').submit();
});
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
0

I found the other answers helpful but to truly achieve what I needed of individual actions based on each option click this was exactly what I needed:

jquery: option plus class and click

Community
  • 1
  • 1
james
  • 23
  • 1
  • 5