Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Multi Select Option - Check if a option is selected or not

I have a 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 am trying to do is check if option "All" is selected or not in jQuery.

What I have tried is

<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 is not working.

Can anyone help me please?

Thanks in advance for helping.

like image 518
Abrar Jahin Avatar asked Dec 02 '14 04:12

Abrar Jahin


1 Answers

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 fiddle

Multi Select

like image 80
AB Vyas Avatar answered Oct 14 '22 03:10

AB Vyas