Using jQuery/Javascript, when a user clicks submit I need to validate if at least one option has been chosen on a select form, and one hasn't been chosen, I need them all to be submitted.
So on a form like this:
<form action="http://example.com" method="get" id="carfare" name="mycarform">
<select name="car" id="carchoice" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input id="carsubmit" type="submit">
</form>
If the user clicks the submit button without choosing any options, I need it to return: http://example.com/?car=volvo&car=saab&car=opel&car=audi
First, check if there are any items selected by doing
if(!$('#carchoice').val())
then, set them all selected by
$('#carchoice option').prop("selected", true);
$('form').submit(function(){ if(!$('#carchoice').val()){ $('#carchoice option').prop("selected", true); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form action="http://example.com" method="get" id="carfare" name="mycarform"> <select name="car" id="carchoice" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <input id="carsubmit" type="submit"> </form>
On submit check if option is selected, if not select all.
$(document).ready( function () {
$('#carefare').submit( function () {
var choice = $('#carchoice').val();
if(!choice) {
$('#carchoice option').attr('selected','selected');
}
});
});
refer jsfiddle check network tab for submitted values
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.