JQuery Multi Select Option - check if an option is selected or not.
I have an HTML Multi select box
<form action="form_action.php" method="Post"> <select name="cars[]" multiple id="select_id"> <option value="all" id="option_id">All</option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <input type="submit"> </form>
What I'm trying to do is check if the "All" option is selected or not in jQuery.
What I tried
<script> $(document).ready(function() { $('#option_id') .click( function() { if ($("#select_id option[value='all']").length == 0) { //value does not exist so add //Do something if not selected } else { //DO something if selected } //$("#select_id option:selected").removeAttr("selected"); //Remove //$("#select_id option").attr('selected', 'selected'); //Add } ); }); </script>
But it does not work.
Can anybody help me?
Thanks in advance for your help.
Please do as below code
$('#option_id').click(function(){ if ($("#select_id option[value=all]:selected").length > 0){ alert('all is selected'); } else{ //DO something if not selected } //$("#select_id option:selected").removeAttr("selected"); //Remove //$("#select_id option").attr('selected', 'selected'); //Add });
You can check below script
From what I see, you are trying to determine if it was selected when changing the parameter in the <select>
field, right?
Try the following:
$("#select_id").change(function () { if ($(this).find("option:selected").val() == "all") { // all is selected } else { // all isn't selected } });