简体   繁体   English

jQuery单选按钮仅选择一个(ID)

[英]jQuery radio button select only one (ID)

I have 2 groups raido buttons, they have different unique IDs, how to make they can be selected only one for each group. 我有2组raido按钮,它们具有不同的唯一ID,如何使它们只能为每个组选择一个。 Thanks 谢谢

<group>
<input type="radio" id="u1"/>1
<input type="radio" id="u2"/>2
<input type="radio" id="u3"/>3
</div >
</group>


<group>
<input type="radio" id="T1"/>4
<input type="radio" id="T2"/>5
<input type="radio" id="T3"/>6
</group>

http://jsfiddle.net/pZdWu/ http://jsfiddle.net/pZdWu/

I don't want to change the html, just want to use jQuery to achieve 我不想更改html,只想使用jQuery来实现

If you really must use the existing HTML, then I'd suggest amending the HTML via jQuery to simply use the default functions of a radio input: 如果确实必须使用现有的HTML,那么建议您通过jQuery修改HTML,以简单地使用单选输入的默认功能:

​$('group').each(
    function(i,e){
        $(e).find('input:radio').attr('name', 'group' + i);
    });​​​​​

JS fiddle demo . JS小提琴演示

References: 参考文献:

Give each item in the group a common name using the name attribute..... 使用name属性给组中的每个项目一个通用名称。

<input type="radio" name="group1" id="u1"/>1
<input type="radio" name="group1" id="u2"/>2
<input type="radio" name="group1" id="u3"/>3

Using jQuery, you can use something like this: 使用jQuery,您可以使用以下代码:

http://jsfiddle.net/pZdWu/5/ http://jsfiddle.net/pZdWu/5/

$(document).ready(function () {
    $("input[type=radio]").click(function () {
        var $this = $(this);
        $this.siblings("input[type=radio]").prop("checked", false);
    });
});

But this assumes your HTML structure is exactly as you provided. 但这假设您的HTML结构与您提供的完全相同。

If the radio buttons have any kind of wrapping HTML on them, or are grouped inside any way, the use of siblings won't work. 如果单选按钮上有任何包装HTML的内容,或者以任何方式组合在其中,则siblings将无法使用。 You might have to use something like: 您可能必须使用类似:

http://jsfiddle.net/pZdWu/7/ http://jsfiddle.net/pZdWu/7/

$(document).ready(function () {
    $("input[type=radio]").click(function () {
        var $this = $(this);
        $this.parents("group:first").find("input[type=radio]").not($this).prop("checked", false);
    });
});

And obviously change the use of "group" to whatever you are actually using (I thought I saw you edited your original question to not use <group> ). 显然,将“ group”的使用更改为您实际使用的任何东西(我以为我看到您编辑了原始问题以不使用<group> )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM