Reputation: 63
if there is a page with multiple select forms on it as below and the form needs to be submitted using js (but not inline), then is there a simple way to achieve it using just one function?
<form action="" method="post">
<select name="cars" id="cars">
<option value="">Choose</option>
<option value="1">Toyota</option>
<option value="2">Nissan</option>
</select>
</form>
<form action="" method="post">
<select name="trucks" id="trucks">
<option value="">Choose</option>
<option value="1">TATA</option>
<option value="2">Nissan</option>
</select>
</form>
If I had to do it in line, it would be simply
onchange = 'this.form.submit();
How do I do this using a js file. Thanks.
Upvotes: 1
Views: 57
Reputation: 6124
Using jQuery:
$(document).ready(function() {
$('select').on('change', function() {
$(this).parents('form').submit();
});
});
EDIT:
As per your request, if I understood you correctly:
1) Put the code above as is in the submit.js
file.
2) In your html/php file reference the script by <script src="submit.js"></script>
Upvotes: 2
Reputation: 318302
You can just target the selects and submit the parent form.
Preferably you'd add classes to those selects, but you could just get all selects
[].slice.call( document.getElementsByTagName('select') ).forEach(function(el) {
el.addEventListener('change', function() { this.form.submit() });
});
Upvotes: 1