Reputation: 1885
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
Reputation: 20015
The problem with your code is that:
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)) {
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
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
Reputation: 240928
Listen to the change
event of the #choose
element, and add your conditional logic there.
$('#choose').on('change', function () {
if (this.value === "2") {
$("#hide-me").hide();
} else {
$("#hide-me").show();
}
});
..equivalent, but perhaps less readable version:
$('#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) { ... }
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
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");
})
Upvotes: 2