Reputation: 3522
I have the following fiddle: http://jsfiddle.net/4Ly1973u/.
Here's my html:
<article>
<select>
<option name='First' value='first'>First</option>
<option name='Second' value='second'>Second</option>
<option name='Third' value='third'>Third</option>
</select>
<div data-name='first' class='show'>
This one should show by default.
</div>
<div data-name='second'>
only visible when "second" is selected
</div>
<div data-name='third'>
only visible when "second" is selected
</div>
</article>
Basically, I want to have the first div show by default, but when you change the select to second or third, I want it to change to that div.
I realize I could do this easy with an if statement, but I could potentially have a lot of select options, so I'm hoping for a cleaner solution. Or is this the only way?
Upvotes: 1
Views: 63
Reputation: 5948
Here a working fiddle: http://jsfiddle.net/4Ly1973u/3/
<article>
<select>
<option name='First' value='first'>First</option>
<option name='Second' value='second'>Second</option>
<option name='Third' value='third'>Third</option>
</select>
<div id='first' class='show'>This one should show by default.</div>
<div id='second' class='noshow'>only visible when "second" is selected</div>
<div id='third' class='noshow'>only visible when "third" is selected</div>
</article>
CSS
.show {
display: block;
}
.noshow {
display:none;
}
jQuery
$(function () {
$("select").change(function () {
$('.show').removeClass('show').addClass('noshow');
var getValue = $("select option:selected").val();
$("#" + getValue).removeClass('noshow').addClass('show');
});
});
Upvotes: 0
Reputation: 77482
Try this
$(function () {
$("select").on("change", function () {
$('.show').removeClass('show');
$('div[data-name="' + $(this).val() + '"]').addClass('show');
});
});
Demo: http://jsfiddle.net/4Ly1973u/1/
Upvotes: 3