1

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?

Joe Morano
  • 1,715
  • 10
  • 50
  • 114
  • Check out [selectedIndex](http://www.w3schools.com/jsref/prop_select_selectedindex.asp) and use that in conjunction with the change() event. – Damon Feb 01 '15 at 01:14

3 Answers3

2

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

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

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';
    }
});
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

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.

gvlasov
  • 18,638
  • 21
  • 74
  • 110