简体   繁体   中英

data-toggle=“buttons” bootstrap radio button not being recognized in JavaScript

I'm trying to hide a div( #asideform ) when I click a radio button and it works if I remove the data-toggle="buttons" from the main div (which is needed for styling), but not if I let it there.

Am I expressing it correctly in the JavaScript code?

HTML:

<div class="btn-group form-group col-xs-6" data-toggle="buttons">
    <label style="float: left; margin-bottom: 0;">Owns 50% +</label>
    <br>
    <label style="margin-top: 1%" class="btn btn-primary active rdio50">
        <input type="radio" name="rdio50" id="foyes" name="foyes" autocomplete="off"  checked> Yes
    </label>
    <label style="margin-top: 1%" class="btn btn-primary rdio50">
        <input type="radio" name="rdio50" id="fono" name="fono" autocomplete="off"> No
    </label>
</div>

JavaScript:

$(function () {
    $("input[name='rdio50']").click(function () {
        if ($("#fono").is(":checked")) {
            $("#asideform").show();
        } else {
            $("#asideform").hide();
        }
    });
});

Check this example, I think this is what you mean. Fiddle

$('.btn-group').click(function() {
   if($('#fono').is(':checked')) { $('#asideform').show(); }

   else{ $('#asideform').hide();}
});

When use data-toggle="buttons" , you click target is the label of radio that's why your click event on input radio will not fire.

So, just use change event to watch radio value, even label click will fire input change, then it worked.

So, replace

$("input[name='rdio50']").click(function () {...});

with

$("input[name='rdio50']").change(function () {...});

Here is the working example:

 $(function() { $("input[name='rdio50']").change(function() { if ($("#fono").is(":checked")) { $("#asideform").show(); } else { $("#asideform").hide(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.js"></script> <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" /> <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.css" rel="stylesheet" /> <div class="btn-group form-group col-xs-6" data-toggle="buttons"> <label style="float: left; margin-bottom: 0;">Owns 50% +</label> <br> <label style="margin-top: 1%" class="btn btn-primary active rdio50"> <input type="radio" name="rdio50" id="foyes" name="foyes" value="yes" autocomplete="off" checked>Yes </label> <label style="margin-top: 1%" class="btn btn-primary rdio50"> <input type="radio" name="rdio50" id="fono" name="fono" value="no" autocomplete="off">No </label> </div> <div id="asideform"> this is the asideform </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