简体   繁体   中英

Show & hide a div using a radio select

I am trying to show a section of my code depending on what the user selects via a radio button. Essentially, I want the elevator_choice to show up only if the users selects 'Second' in the first set of buttons.

HTML:

<div class="row" style="padding: 0 0 10px 0;">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="floor" value="First">First
        </label>
        <label class="btn btn-default">
            <input type="radio" name="floor" value="Second">Second
        </label>
    </div>
</div>
<div class="row" style="padding: 0 0 10px 0; display:none;" id="elevator_choice">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="elevator" value="No">No
        </label>
    </div>
</div>

JQuery:

$(document).ready(function() {
   $("input[name$='floor']").click(function() {
       if($(this).val() == 'First') {
            $('#elevator_choice').hide();           
       }
       else {
            $('#elevator_choice').show();   
       }
   });
});

JsFiddle

Add class name to each radio input and register click event on this input, before showing check whether the text is first or not.


<div class="row" style="padding: 0 0 10px 0;">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input class="check" type="radio" name="floor" value="First">First
        </label>
        <label class="btn btn-default">
            <input class="check" type="radio" name="floor" value="Second">Second
        </label>
    </div>
</div>
<div class="row" style="padding: 0 0 10px 0; display:none;" id="elevator_choice">
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="elevator" value="No">No
        </label>
    </div>
</div>


$(document).ready(function() {
   $('.check').click(function() {
       if($(this).val() == 'Second') {
            $('#elevator_choice').show();           
       }
       else {
            $('#elevator_choice').hide();   
       }
   });
});

Ok, I figured out the problem. I am using Twitter Bootstrap and for some reason Bootstrap adds some style to the buttons so that the 'onclick' event does not work. I changed it to 'onchange' and it works now.

Thanks everyone

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