简体   繁体   中英

jQuery if input[type=“radio”] before clickable label hasn't attribute “checked” then do NOT add it, else do nothing

please help me to implement this behavior. I would like to check if after click on a label next to radiobutton this radiobutton already has attribute "checked" then it's ok, let's stay in this stage. But if this element hasn't this attribute, then i won't add it. This is what i gave birth:

$.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};
var lab = $(".rating input[type='radio'] + label");
lab.click(function {
    if ($(this).lab.prev('input').hasAttr('checked')) {
        alert("OK");
    };
});

This is a JSFiddle

Please help me guys. Thanks in advance!

$('#ret_info_srars1 label').on('click', function(e) {
    e.preventDefault();
    if($(this).prev('input[type=radio]').is(':checked'))
        alert("OK!");
});

jsfiddle DEMO

The correct way to figure out whether a radio button is checked in jQuery is:

$("input:radio").is(':checked')

There is also the change event for radio buttons that you can use:

$('.rating input:radio').change(function(){
    if ($(this).is(':checked'))
    {
        alert ("changed and checked");
    }
});    

See it working in a fiddle

To set a radio button to be checked use .prop

$("input:radio").prop("checked", true)

Or you can just write:

$(lab).is(':checked')
{
alert("Radio Button Checked");
}

as lab has already been assign with the desired ID.

OR

if($("#RadioButtonID).is(':checked'))
{
alert("Radio Button Checked");
}
else
{
alert ("Not Checked");
}

If your goal is truly to create a "read-only" set of radio buttons as you indicated in the comments above, the simplest solution is to disable the radio buttons:

$('input[type="radio"]').prop('disabled', true);

Here's your updated fiddle: http://jsfiddle.net/voveson/25d3bja7/3/

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