简体   繁体   中英

Cannot deselect radio button?

I have been attempting to allow radio buttons to be deselected using jQuery, but I am running into issues with the prop function. When this code runs, my conditional ( $(e.currentTarget).prop('checked') ) always evaluates to true.

Here is a fiddle which demonstrates my issue: Jsfiddle

FYI: I am using jQuery 1.8.2, and I cannot update it because it is a legacy project with many dependencies. Also, I MUST use radio buttons per the client's request.

Javascript:

$("input[name=optionMedia]").click(function(e) {
    if ($(e.currentTarget).prop('checked')) {
        $(e.currentTarget).prop('checked', false);
    }
});

Html:

<input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/>
<input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

You can do it like this

 $('input.bigSizeInput').mouseup(function() { if ($(this).is(':checked')) { setTimeout(function() { $('input.bigSizeInput:checked').prop('checked', false); }, 1) } })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1" /> <input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

This is because checked is a property. If its there it is true, if its not it is not true. Hence you either should switch to a checkbox or use

$("..").removeProp('checked')

Using checkbox to check/uncheck is better than radio button. But if you want to use radio button, you need to check if radio is checked, copy it using and remove checked attribute of copied element and then insert it after target radio. At the end remove original radio.

 $(document).on("mousedown", "input[name=optionMedia]", function(e) { if (this.checked) $(this).clone().prop('checked', false).insertAfter(this).end().remove(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <input class="bigSizeInput" type="radio" id="audioVideo" name="optionMedia" value="1"/> <input class="bigSizeInput" type="radio" id="showReel" name="optionMedia" value="2" />

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