简体   繁体   中英

Hiding/showing div using radio buttons

I am trying to hide and show a single div when a radio button is selected in bootstrap. I cannot get it to work. Here is my current code: http://jsfiddle.net/pLqmS/9/

    <div class="row demo-row">
        <div class="span7">
            <div id="opt1" class="option">
            <h5>Generation</h5>  
        </div>
        <div id="opt2" class="option" style="display: none;">
            <h5>Test</h5>
        </div>
        <div id="opt3" class="option" style="display: none;">
            <h5>Test</h5>
        </div>
        <div id="opt4" class="option" style="display: none;">
            <h5>Test</h5>
        </div>
    </div>

Here is my script:

$('.phone-choice').click(function () {
$('.option').each(function () {
    if ($(this).is(':visible')) {
        $(this).stop().slideUp('slow');
    }
});
var id = $(this).val();
$('#opt' + id).stop().slideDown('slow');
});

Any ideas?

You are duplicating the ids, you should never do that. Not only that it makes the html invalid, but also the selector will end up selecting the element with the same id that appears first in DOM. Id of your radio button and target divs are same. You can instead make them classnames.

With the simplified version you could do this:

Markup

  <div  class="option opt1">
                <h5>Generation</h5> 
        </div>
        <div  class="option opt2" style="display: none;">
                <h5>Test</h5>

        </div>
        <div class="option opt3" style="display: none;">
                <h5>Test</h5>

        </div>
        <div  class="option opt4" style="display: none;">
                <h5>Test</h5>

        </div>

Js

$('.phone-choice').change(function () {
    $('.option:visible').stop().slideUp('slow');
    var id = this.value;
    $('.' + id).stop().slideDown('slow');
});

Demo

If you want to target based on position (index) of the element you could try this:

$('.phone-choice').change(function () {
    var $this = this
    $('.option:visible').stop().slideUp('slow', function () {
       $('.option').eq($('phone-choice').index($this)).slideDown('slow');
    });
});

FIddle

You have duplicated ids for your HTML elements. Note that the input elements share ids of some of the div elements

 <div id="opt1" class="option" style="display: none;">
 <input type="radio" class="phone-choice" name="optionsRadios" id="opt1" value="opt1" data-toggle="radio" checked></label>

You also have an unclosed div tag

        <div class="span7">
            <div id="opt1" class="option">
            <h5>Generation</h5>  
        </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM