0

How to check if value is not blank in this code using Java Script or jQuery?

<select name="producttype" class="selectOption">
    <option class="selectOption" value="blank">Select something</option>
    <option class="selectOption"  value="test1">Test1</option>
    <option class="selectOption"  value="test2">Test2</option>
    <option class="selectOption"  value="test3">Test3</option>
</select>
3
  • 3
    Next time, please post what you've tried. Commented Aug 7, 2013 at 15:49
  • 1
    @Jeffman - this time would be helpful as well. Commented Aug 7, 2013 at 15:52
  • I commented after an answer had been posted. The point seemed moot for this time around. Commented Aug 7, 2013 at 15:55

3 Answers 3

1

Using jQuery:

$(".selectOption").on("change", function() {
    if ($(this).val() != "blank")
        // Do something
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can do:

$("select[name=producttype]").change(function() {
    if (!(this.value == "blank"))
        console.log("not blank!");
});

4 Comments

This won't work. this.value is not defined for a select object. You will have to do jQuery(this).val().
Ah, interesting. I guess this must be something recent. Previously you had to get it from select.options[select.selectedIndex].value. Old habits die hard, I guess. :)
It works, because it's using the DOM object with Javascript. But it looks "ugly" because it's part jQuery, part native JS.
@MelanciaUK Thanks for the explanation; learnt something new.
0

It should be as simple as:

if(jQuery("select.selectOption").val() !== "blank") {
    ...
}

Or if you're checking to see that the value is not blank on a change event:

jQuery("select.selectOption").on("change", function() {
    if(jQuery(this).val() !== "blank") {
        ...
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.