简体   繁体   中英

Setting a radio button to checked in jquery not showing it as checked in view

On document ready I'm setting a radio button to checked, I want the user to see the button as highlighted/discolored. But nothing is showing in the view. Here is my html. Nothing shows it as being checked in the view or HTML. It's the same color as all the other radio buttons.

<div class="btn-group" data-toggle="buttons" id="SpaceType">
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="0" autocomplete="off"> House
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="1" autocomplete="off"> Apartment
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="2" autocomplete="off"> Studio
                    </label>
                    <label class="btn btn-primary">
                        <input type="radio" name="typeoptions" id="3" autocomplete="off"> Other
                    </label>
                </div>

Here is my jquery.

if ($("#YogaSpaceType").val() != "") {
    var t = $("#YogaSpaceType").val();
    var element = '#SpaceType.' + t;
    //$(element).prop('checked', true);
    $('input:radio[id=SpaceType][id=0]').prop('checked', true);
}

I tried both lines including the one that is commented out. If I add 'checked' to the element like below the HTML shows it as checked but I see nothing in the view as checked, it still looks unchecked.

<input type="radio" name="typeoptions" id="0" autocomplete="off" checked> House

It looks like you want to change this a bit to be more like http://www.mkyong.com/jquery/how-to-select-a-radio-button-with-jquery/ . The problem here is you are trying to use the input keyword in jquery, but your html is button groups.

From that page, the HTML is: <input type="radio" name="sex" value="Male">Male</input> <input type="radio" name="sex" value="Female">Female</input> <input type="radio" name="sex" value="Unknown">Unknown</input>

and then the JS is $('input:radio[name=sex]')[2].checked = true;

If it's necessary to leave them as button groups, you'll need to change your JS line to be more like $("#0").prop('checked', true) . You could also chain the div ids together like this: $("#SpaceType #0").prop('checked', true);

It was a little confusing, but the class attribute 'active' needs to be added to the label. Not the checked attribute. This is a little confusing but understood now.

$('input[type="radio"][id="0"]').prop('checked', true)

id的多值检查将以0个元素结束。

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