I have the following form. I\'d like it to be submitted automatically via jQuery when the user makes a selection, without needing to press the submit button. How do I do thi
Your form is missing an action value, which prevents submitting the form at the end. But in the mid-time you should correct this code:
$(document).ready(function() {
$('#cars').on('change', function() {
document.forms[myFormName].submit();
});
});
You can also submit a form by triggering submit button click event:
$(document).ready(function() {
$('#cars').on('change', function() {
var $form = $(this).closest('form');
$form.find('input[type=submit]').click();
});
});
My solution is create hidden submit button and click it on change event .
<select name="id" onchange="javascript:$('#submit').click();">
<option value="0">Please Select Web Site</option>
<option value="1">------</option>
<option value="2">-------</option>
</select>
<button id="submit" class="hidden" type="submit" name="submit" value="Submit"/>
In my case, this works perfectly well, and it works with or without the submit button.
<form action="" method="post">
<select name="id" id="cars">
<option value="">Choose</option>
<option value="1">Toyota</option>
<option value="2">Nissan</option>
<option value="3">Dodge</option>
</select>
</form>
<script type="text/javascript">
jQuery(function() {
jQuery('#car').change(function() {
this.form.submit();
});
});
</script>
I know this is a bit old (and already answered), but none of the answers was quite as flexible as I wanted, so below is the solution I ended up with:
$(document).ready(function() {
$('#cars').change(function() {
var parentForm = $(this).closest("form");
if (parentForm && parentForm.length > 0)
parentForm.submit();
});
});
Just use assistance of JavaScript.
<select onchange="this.form.submit()">
...
</select>
An even quicker version of the code would look something like.
<form action="" method="post">
<select name="id" id="cars" onchange="javascript:this.form.submit()">
<option value="">Choose</option>
<option value="1">Toyota</option>
<option value="2">Nissan</option>
<option value="3">Dodge</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
Now what we are doing is adding
onchange="javascript:this.form.submit()"
to any field that you want the submit action to fire on. Of course this only works on elements that support the onchange html property