Joe Morano
Joe Morano

Reputation: 1885

Checking value of an html select with jQuery

I have the following select box:

<select id="choose">
  <option value=1>A</option>
  <option value=2>B</option>
  <option value=3>C</option>
</select>

<div id="hide-me">hide me!</div>

How can I hide an element when I select option "B"? I tried this:

<script type="text/javascript">
  if ("#chose option:selected").val(2) {
    $("#hide-me").hide();
  };
</script>

I think I'm close, but nothing happens when I select option "B". Anyone have any suggestions?

Upvotes: 1

Views: 80

Answers (3)

gvlasov
gvlasov

Reputation: 20015

The problem with your code is that:

  1. It is not syntactilally correct — ("#chose option:selected").val(2) is an expression, which in turn should be wrapped in parentheses to be a proper condition for if, like this:

    if (("#chose option:selected").val(2)) {

  2. However, even after that your code is not correct because you're not actually using jQuery. You're calling method .val() just on a string "#chose option:selected", whereas that string should instead be a jQuery selector passed to jQuery itself:

    if ($("#chose option:selected").val(2)) { // $ is the jQuery object that does all the work

  3. However2, even that is incorrect, because you'd just be checking the value of an element right away. What you need is to wait for an element to be changed. Other answers explain very well how to do that.

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240928

Listen to the change event of the #choose element, and add your conditional logic there.

Example Here

$('#choose').on('change', function () {
    if (this.value === "2") {
        $("#hide-me").hide();
    } else {
        $("#hide-me").show();
    }
});

..equivalent, but perhaps less readable version:

Example Here

$('#choose').on('change', function () {
    $("#hide-me").toggle(this.value !== "2");
});

As a side note, the value of the selected option is a string.

If you wanted to, you could also convert it to a number:

if (parseInt(this.value, 10) === 2) { ... }

or you could use == rather than ===: (not suggested, though. This could lead to logical errors.)

if (this.value == 2) { ... }

Without jQuery:

Example Here

document.querySelector('#choose').addEventListener('change', function () {
    var element = document.getElementById('hide-me');
    if (this.value === "2") {
        element.style.display = 'none';
    } else {
        element.style.display = 'block';
    }
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to attach change event to select element to detect the option change. then use .toggle() with argument value not equal to 2 for making show/hide decision :

$('#choose').change(function(){
   $("#hide-me").toggle($(this).val() != "2");
})

Working Demo

Upvotes: 2

Related Questions