Reputation: 3191
I am attempting to use JavaScript and/or jQuery to hide certain html elements based on which item is selected in a drop down menu. The page looks like this:
[Drop down menu]
[text field 1]
[text field 2]
[text field 3]
[text field 4]
[text field 5]
The drop down menu has 3 options. For the first option, fields 1-4 should show. For the second, 2-4, and for the third fields 2-5 should be available.
I've got a JSFiddle demo here. Specifically, I don't get why
<option value="option3.com" onselect="$('#five').hide()">option3.com</option>
doesn't hide '#five'
Upvotes: 0
Views: 1135
Reputation: 318182
Firstly, there is no onselect
, you probably wanted onchange
.
Secondly, you're using jQuery, so use it.
Thirdly, change the markup to somehow include what you want, data attributes are great.
<select style="width: 120px;" name="farm_in" id="farm_in">
<option></option>
<option value="option1.com" data-show="[1,2,3,4]">option1.com</option>
<option value="option2.com" data-show="[2,3,4]">option2.com</option>
<option value="option3.com" data-show="[2,3,4,5]">option3.com</option>
</select>
<br>
<input style="width: 120px;" type="text" name="one" id="el1" value="one">
<br>
<input style="width: 120px;" type="text" name="two" id="el2" value="two">
<br>
<input style="width: 120px;" type="text" name="three" id="el3" value="three">
<br>
<input style="width: 120px;" type="text" name="four" id="el4" value="four">
<br>
<input style="width: 120px;" type="text" name="five" id="el5" value="five">
Then all you have to do is
$('#farm_in').change(function() {
$('input').hide();
$('#el' + $('option:selected', this).data('show').join(', #el')).show();
});
Upvotes: 1
Reputation: 85
Looking at you fiddle you are missing the ID attributes for your text fields.
<input style="width: 120px;" type="text" name="five" value="five">
Should be:
Also I would recommend splitting you JS from your HTML.
Upvotes: 0
Reputation: 218828
For starters, this doesn't identify an element in your DOM:
$('#five')
You don't have an element with an id
of "five"
. Instead, you're looking for this:
$('input[name="five"]')
(Or, conversely, you could give an id
attribute to your elements.)
Aside from that, I'm not aware of any onselect
event for an option
element. Why not respond to the change
event of the select
instead (and de-couple from the markup a bit while you're at it)?:
$('select').on('change', function () {
if ($(this).val() === 'option3.com') {
$('input[name="five"]').hide();
} else {
$('input[name="five"]').show();
}
});
Upvotes: 1