简体   繁体   中英

how to select only one checkbox using jquery?

I am using checkbox in the asp.net gridview. I want select only one checkbox at time. if I select one checkbox other checkboxes should be deselected.

I have html view source

<input id="ctl00_MainContent_mGrid_ob_mGridBodyContainer_ctl02_ctl02_ctl00_ChkID" type="checkbox" 
<input id="ctl00_MainContent_mGrid_ob_mGridBodyContainer_ctl03_ctl02_ctl00_ChkID" type="checkbox"

Use a radio button instead of a checkbox.

<form>
    <input type="radio" name="parents" value="Mom" /> Mom<br />
    <input type="radio" name="parents" value="Dad" /> Dad
</form>

Usually radio buttons are used for the exclusive functionality where only one item in a group is selected and the browser will do taht for you automatically with the right HTML.

For checkboxes, you could code it with jQuery like this:

<div class="checkboxContainer">
    <input id="ctl00_MainContent_mGrid_ob_mGridBodyContainer_ctl02_ctl02_ctl00_ChkID" type="checkbox"> Item 1<br>
    <input id="ctl00_MainContent_mGrid_ob_mGridBodyContainer_ctl03_ctl02_ctl00_ChkID" type="checkbox"> Item 2<br>
    <input id="ctl00_MainContent_mGrid_ob_mGridBodyContainer_ctl04_ctl02_ctl00_ChkID" type="checkbox"> Item 3
</div>​

$("input[type='checkbox']").change(function() {
    $(this).closest(".checkboxContainer").find("input[type='checkbox']").not(this).prop("checked", false);
    $(this).prop("checked", true);
});

​ Working Demo: http://jsfiddle.net/jfriend00/hWEXx/

Here's the pure HTML way of doing exclusive radio buttons (also in that same demo):

<div class="radioGroup">
    <input type="radio" name="group1">Item A<br>
    <input type="radio" name="group1">Item B<br>
    <input type="radio" name="group1">Item C<br>
</div>

in asp.net you should use radiobuttons instead checkboxes (in this case)

<div class="group">
   <asp:RadioButton Id="radio1" runat="server" GroupName="radioGroup" />
   <asp:RadioButton Id="radio2" runat="server" GroupName="radioGroup" />
</div>

GroupName attribute make this functionality you need. (If radio1 is Checked the radio2 is automatically unchecked. hope this help:)

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