[英]How to undo a radio button selection using JavaScript or preferably jQuery
I am working in a scenario with a group of radio button selections. 我正在使用带有一组单选按钮选择的方案。 The requirement is that only 2 can be selected Yes. 要求是只能选择2个。是。 So, if the third is also selected "Yes", I want to revert it to "No" 因此,如果第三个也选择“是”,我想将其恢复为“否”
Additionally I would also like to know if I can just check if a given index of Radio button within a group is checked instead of doing this: "($(this).is(':checked') && $(this).val() == 'Y')" 另外,我还想知道是否可以检查是否检查了组中单选按钮的给定索引,而不是这样做:“($(this).is(':checked')&& $(this).val ()=='Y')”
jsFiddle Link: http://jsfiddle.net/pshah331/S8qep/ jsFiddle链接: http : //jsfiddle.net/pshah331/S8qep/
HTML: HTML:
<p>Folder A:
<input type="radio" name="folder_A" value="Y" onclick="folderSelectionChanged()" />Yes
<input type="radio" name="folder_A" value="N" onclick="folderSelectionChanged()" />No</p>
<p>Folder B:
<input type="radio" name="folder_B" value="Y" onclick="folderSelectionChanged()" />Yes
<input type="radio" name="folder_B" value="N" onclick="folderSelectionChanged()" />No</p>
<p>Folder C:
<input type="radio" name="folder_C" value="Y" onclick="folderSelectionChanged()" />Yes
<input type="radio" name="folder_C" value="N" onclick="folderSelectionChanged()" />No</p>
<div id="update"></div>
JavaScript in "HEAD": “ HEAD”中的JavaScript:
function folderSelectedYesCount() {
var yesCount = 0;
var folderRadioGroups = $("input[name^='folder_']");
folderRadioGroups.each(function () {
// TODO: Would like to check by index --> "index 0 is selected/checked"
if ($(this).is(':checked') && $(this).val() == 'Y') {
yesCount++;
}
});
return yesCount;
}
function folderSelectionChanged() {
// TODO: If count of Yes is greater than 2, then change the last clicked to "No"
/*
if (folderSelectedYesCount() > 1){
$(this)[1].prop('checked', true);
}
*/
$('#update').html('Selection count for "Yes" is <b>' + folderSelectedYesCount() + ' </b>');
}
I have updated your jsfiddle please check :- 我已经更新了您的jsfiddle,请检查:-
function folderSelectionChanged(e) {
if(folderSelectedYesCount()>2){
$(e).siblings().prop("checked",true);
}
$('#update').html('Selection count for "Yes" is <b>' + folderSelectedYesCount() + ' </b>');
}
click here :- http://jsfiddle.net/S8qep/47/ 点击这里: -http : //jsfiddle.net/S8qep/47/
Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.