Hide/show content if some option is selected with bootstrap
24,209
Solution 1
you can use collapse from bootstrap:
HTML:
<select id="mystuff">
<option value="0">-- Choose One --</option>
<option value="opt1">House</option>
<option value="opt2">Car</option>
<option value="opt3">Bicycle</option>
</select>
<div class="mystaff_hide mystaff_opt1">
some content to show on option House selected
</div>
<div class="mystaff_hide mystaff_opt2">
some content to show on option Car selected
</div>
<div class="mystaff_hide mystaff_opt3">
some content to show on option Bicycle selected
</div>
javascript/jquery
//add collapse to all tags hiden and showed by select mystuff
$('.mystaff_hide').addClass('collapse');
//on change hide all divs linked to select and show only linked to selected option
$('#mystuff').change(function(){
//Saves in a variable the wanted div
var selector = '.mystaff_' + $(this).val();
//hide all elements
$('.mystaff_hide').collapse('hide');
//show only element connected to selected option
$(selector).collapse('show');
});
if need more code block connect do one select option, only add class "mystaff_hide" and class "mystaff_[option value]"
Solution 2
Bootstrap is built on top of jQuery, so let's use that:
- First, we assign an ID to the select control (mystuff)
<select id="mystuff">
- Then, we tell jQuery to watch for the value of that element to change:
$('#mystuff').change(function() {
- Next, we grab the value of teh currently selected item:
opt = $(this).val();
- Then, determine which option was selected
if (opt=="opt1"){}
//Note that are testing the VALUE, not the text, of the option - Finally, inject some html into the DIV with
id=msgbox
$('#msgbox').html('some html code');
HTML:
<select id="mystuff">
<option value="0">-- Choose One --</option>
<option value="opt1">House</option>
<option value="opt2">Car</option>
<option value="opt3">Bicycle</option>
</select>
<div id="msgbox"></div>
javascript/jquery
$('#mystuff').change(function() {
opt = $(this).val();
if (opt=="opt1") {
$('#msgbox').html('<h2>My House</h2>I have a large house on a quiet street');
}else if (opt == "opt2") {
$('#msgbox').html('<h2>My Car</h2>I drive an Audi A200');
}else if (opt == "opt3") {
$('#msgbox').html('<h2>My Bicycle</h2>I do not need a bicycle, I have a car.');
}
});
Author by
Luis Serrano
Updated on November 24, 2020Comments
-
Luis Serrano over 3 years
How can I show some content if users select one option using select/option tag? I'm using bootstrap and I know how to collapse content but I'm using checkbox's for this or buttons but for this I can't make it work..
Someone knows how to do it?