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 this?
<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>
<input type="submit" name="submit" value="Submit">
</form>
adeneo, I tried your suggestion but it's still not working. Here's the complete code, anything wrong?
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#cars').on('change', function() {
this.form.submit();
});
});
</script>
</head>
<body>
<form action="" method="post">
<select name="id" id="cars">
<option value="">Select...</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>
</body>
</html>
You can do it using a simple javascript. Here onChange event will be invoked whenever user changes the value in the select box and this. form. submit() method will submit the form.
To submit a select form on a change event (without a submit button) in React, you have to do two things: use the "onChange" property to fire a function to send the value. in this function, you have to trigger the submit action of the form.
The Submit Button The <input type="submit"> defines a button for submitting the form data to a form-handler. The form-handler is typically a file on the server with a script for processing input data. The form-handler is specified in the form's action attribute.
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();
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With