Clinton Green Clinton Green - 27 days ago 9
jQuery Question

jQuery - Prevent Select Value from substituting text if no val is present

I have a select and the first option is normally "Please select blah, blah, blah" and has no value so when I do a check using the code below, I get a value of "Please select an option" for the first option. How do I prevent this?

See here for an example, https://jsfiddle.net/nvcc84st/

CODE

<select>
<option>Please select an option</option>
<option value="one">Option One</option>
<option value="two">Option Two</option>
<option value="three">Option Three</option>
</select>

$('select').on('change', function(){
if ( $(this).val ) {
// do something
}
});

Answer

I don't believe you can prevent this value from going to your JQuery code. However you could just test for it and discard.

$('select').on('change' function() {
    if ($(this).val() == "Please select an option") {
        // do nothing
    } else {
        // do something
    }
});

Or

$('select').on('change' function() {
    if ($(this).val() != "Please select an option") {
        // do something
    }
});
Comments