How do I allow to check only one checkbox out of four in UserControl?
I have created a User Control with 4 check boxes(server control). I want to allow to check only one checkbox out of four.
The user control is loaded on page dynamically.I page ma开发者_运维问答y have multiple same UserConrol.
How do I do it using jQuery or Javascript?
Use a Radio Button Control. Checkboxes are meant for multiple selections, whereas Radio Buttons are meant for single selections. Then with the Radio Buttons you can specify the GroupName
for those controls to limit the selection to a single item.
You can give all of the checkboxes in the group the same class and do something like this to uncheck them all using JQuery, while checking or unchecking the one that was clicked:
$('.checkbox').click(function{
// save the original checked state of the one we're clicking:
var checked = $(this).attr('checked');
$('.checkbox').attr('checked', false); // uncheck all of the boxes
$(this).attr('checked', !checked); // invert the original state
});
But the better choice would probably be to use a radio button control with a "none of the above" option. That way you can do validation (did they answer the question at all?)
I think it should be: $(this).attr('checked', checked);
Had similar issue when working on cakephp. Cakephp wraps checkboxes within DIV. My solution was clear checkboxes using each loop and then select the checkbox user ticked.
CASE:
<div class="unique"> <input type='checkbox' name='mygroup1' value='1' class=''>one</div>
<div class="unique"> <input type='checkbox' name='mygroup2' value='2' class=''>two</div>
<div class="unique"> <input type='checkbox' name='mygroup3' value='3' class=''>three</div>
$('.unique').click(function() {
$('.unique').find('input').each(function(){
$(this).attr('checked', false);
});
$(this).find('input:first').attr('checked', true);
});
精彩评论