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>
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.
This is another method:
$('.myselect').change(function() {
if ($(this).children('option:first-child').is(':selected')) {
//do something
}
});
<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>
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 -->
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With