Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check to see if 1st option is selected

Tags:

jquery

How would I check to see if the first option is selected and then execute some code.

Something like, if select box named "My_Saved_Shipping" has the 1st option selected then execute the code.

<select name="My_Saved_Shipping">
<option>Select/Enter Address</option>
<option value="1">text</option>
<option value="2">text2</option>
</select>
like image 999
user357034 Avatar asked Aug 13 '10 14:08

user357034


4 Answers

if ( $('select[name=My_Saved_Shipping]')[0].selectedIndex === 0 ) {
    // do something
}

It'd be best to give the <select> an id (typically matching the name) - an #id selector is faster than a [attr=val] selector.

like image 192
James Avatar answered Oct 11 '22 07:10

James


This is another method:

$('.myselect').change(function() { 
    if ($(this).children('option:first-child').is(':selected')) {
       //do something
    }
});
like image 39
Mesut Tasci Avatar answered Oct 11 '22 07:10

Mesut Tasci


<script type="text/javascript">
    if($("select[name='My_Saved_Shipping']").selectedIndex == 0)
    {
        //This is where your code goes
        alert('First Element is selected');
    }
</script>

If you want to test for the text within the option, use:

<script type="text/javascript">
    if($("select[name='My_Saved_Shipping']").text == 'Select/Enter Address')
    {
        //This is where your code goes
        alert('First Element is selected');
    }
</script>
like image 11
Brendan Bullen Avatar answered Oct 11 '22 08:10

Brendan Bullen


Edit: Modified selector to work off of name, also added code to wireup to the change handler for the select, and placed in the ready handler.

$(function(){ 
        $("select[name='My_Saved_Shipping']").change(function() {            
            if (this.selectedIndex == 0){
                 <!-- do stuff -->
                }
          });
}); 
like image 3
heisenberg Avatar answered Oct 11 '22 06:10

heisenberg