Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/show content if some option is selected with bootstrap

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.

How can this be done?

like image 697
Luis Serrano Avatar asked Feb 15 '23 04:02

Luis Serrano


2 Answers

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]"

like image 164
sertmo Avatar answered Feb 27 '23 11:02

sertmo


Bootstrap is built on top of jQuery, so let's use that:

  1. First, we assign an ID to the select control (mystuff)
    <select id="mystuff">
  2. Then, we tell jQuery to watch for the value of that element to change:
    $('#mystuff').change(function() {
  3. Next, we grab the value of teh currently selected item:
    opt = $(this).val();
  4. Then, determine which option was selected
    if (opt=="opt1"){} //Note that are testing the VALUE, not the text, of the option
  5. Finally, inject some html into the DIV with id=msgbox
    $('#msgbox').html('some html code');

Working jsFiddle example

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.');
    }
});
like image 20
cssyphus Avatar answered Feb 27 '23 11:02

cssyphus