简体   繁体   English

单击后禁用单选按钮

[英]Disable radio button after click

I have some forms with some radio buttons elements. 我有一些带有一些单选按钮元素的表格。 I want to disable just one of the radios buttons (those named 'option 1') once a button is selected. 一旦选择一个按钮,我只想禁用单选按钮之一(那些名为“选项1”)。 This is the HTML: 这是HTML:

<h2>Option 1</h2>
<form>
  <input type="radio" name="option 1" value="A" />Value A
  <input type="radio" name="option 1" value="B" />Value B
</form>

<h2>Option 2</h2>
<form>
  <input type="radio" name="option 2" value="C" />Value C
  <input type="radio" name="option 2" value="D" />Value D
</form>

And I'm using this code: 我正在使用以下代码:

$(":radio").click(function() {
  var radioName = "option 1"; 
  $(":radio[name='" + radioName + "']:not(:checked)").attr("disabled", true); 
});

It works... but if a radio button 'option 2' is selected first then the 'option 1' radio buttons are disabled (they should remain enabled until clicked). 它可以工作...但是如果首先选择单选按钮“选项2”,则“选项1”单选按钮将被禁用(在单击之前,它们应保持启用状态)。 How can I prevent this behavior? 如何防止这种行为?

Thanks 谢谢

You are attaching the event to all radio buttons, but you should attach the event just to the ones that will disable themselves. 您将事件附加到所有单选按钮,但应仅将事件附加到将禁用它们的按钮。 Check my snippet. 检查我的代码段。

 $('input[type="radio"][name="option 1"]').click(function() { var radioName = "option 1"; $('input[name="' + radioName + '"]:not(:checked)').attr("disabled", true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>Option 1</h2> <form> <input type="radio" name="option 1" value="A" />Value A <input type="radio" name="option 1" value="B" />Value B </form> <h2>Option 2</h2> <form> <input type="radio" name="option 2" value="C" />Value C <input type="radio" name="option 2" value="D" />Value D </form> 

In your jQuery function you select all the radio buttons but what you want is to target only the radio button named option 1 so update you code like this: 在您的jQuery函数中,选择所有单选按钮,但是您只想定位名为option 1的单选按钮,因此可以像这样更新代码:

$(":radio[name='option 1']").click(function() {
  var radioName = "option 1"; 
  $(":radio[name='" + radioName + "']:not(:checked)").attr("disabled", true); 
});

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

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