views:

48

answers:

4

How to convert the onchange="this.form.submit()" to jQuery format?

<form action="process.php" method="post">
  <select name="qty" onchange="this.form.submit()">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</form>

I got a problem because some of browser will do nothing on the process.php if use onchange="this.form.submit()"

Let me know..

+2  A: 

Like this:

$('select[name="qty"]').change(function(){
  $(this).parents('form').submit();
});
Sarfraz
can be done if the select name is `qty[]`?
kampit
Don't forget to bind it after the DOM has loaded: $(document).ready(function(){ //put js here });
Niels Bom
You rather address the form with an id, instead of through the parent which is heavier..
gillyb
Yes I had multiple form here which same name as `qty` but different `action`
kampit
+2  A: 

You don't need to do anything. Whilst you can change this.form.submit() to $(this).closest('form').submit(), this will have no effect (apart from being slightly less readable) as all jQuery will do with that will be to call this.form.submit().

If you have a problem with submitting the form from plain JavaScript, you will still have the same problem submitting it with jQuery. What exactly is that problem?

In any case you should generally not use auto-submitting select boxes. They break keyboard accessibility (since IE fires onchange prematurely from keyboard use) and they interact poorly with the back button.

bobince
Hmm.. correct. I need to find what exactly is that problem.
kampit
A: 

such questions always remember me of things like this. why do you want to use jquery for such a simple thing? give a name to your form and do document.myform.submit(); (which will work in IE3.0+, FF1.0+, Safari1.0+, Opera5.12+, Konqueror3.1+ ... (how about jQuery?)).

oezi
A: 

add an id to form and write:

$('#formid select[name=qty]').change(function(){
    $('#formid').submit();
});
franzose