I am working in a scenario with a group of radio button selections. The requirement is that only 2 can be selected Yes. 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')"
jsFiddle Link: http://jsfiddle.net/pshah331/S8qep/
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":
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>');
}
Changed html so folderSelectionChanged
function can take this
as argument to handle the events like this:
if(folderSelectedYesCount() > 2){
$(obj).prop('checked', false);
$(obj).next().prop('checked', true);
}
I have updated your jsfiddle please check :-
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/
Thanks
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.