Javascript 如何创建具有不同名称的互斥单选按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3216512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:43:07  来源:igfitidea点击:

How can I create mutually exclusive radio buttons with different names?

javascripthtmlradio-button

提问by yogsma

I have a few radio buttons that belong to the same category, but I want to name them differently and make them mutually exclusive. How do I do that? Based on the selected value, I do different actions, and I can't access them if they have the same name.

我有几个属于同一类别的单选按钮,但我想以不同的方式命名它们并使它们相互排斥。我怎么做?根据选定的值,我执行不同的操作,如果它们具有相同的名称,我将无法访问它们。

回答by Konerak

Why can't you access them if they have the same name? You can add IDs(you should), you can distinguish by value or just count them and use the n-th element.

如果它们具有相同的名称,为什么您无法访问它们?您可以添加 ID(您应该添加),您可以通过值进行区分或仅对它们进行计数并使用第 n 个元素。

You should give radiobuttons the same nameto make the browser understand they are exclusive.

应该为单选按钮指定相同的名称,以使浏览器理解它们是独占的。

You could (but should not) hack around this, and give each object a different name. Then add an onSelect/onClick handler for each object, and when the event fires, "uncheck" the other buttons. This is dirty and should be avoided.

您可以(但不应该)解决这个问题,并为每个对象指定不同的名称。然后为每个对象添加一个 onSelect/onClick 处理程序,当事件触发时,“取消选中”其他按钮。这是肮脏的,应该避免。

回答by a7drew

Radio buttons require the same name to be mutually exclusive. However, they can have different ID attribute values, if you want to manipulate them individually with JavaScript.

单选按钮需要相同的名称才能互斥。但是,如果您想使用 JavaScript 单独操作它们,它们可以具有不同的 ID 属性值。

There are lots of ways to get the selected value with jQuery:

有很多方法可以使用 jQuery 获取所选值:

<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />


// value of checked input tag of type 'radio'
var selectedValue = $('input[type=radio]:checked').val();

// value of checked input tag having name of 'foo'
var selectedValue = $('input[name=foo]:checked').val();

// value of the first checked radio button, regardless of name
var selectedValue = $('input:checked').val();

回答by Greg McNulty

If you have to change the name, you can access the DOM and it's elements through JavaScript.

如果必须更改名称,则可以通过 JavaScript 访问 DOM 及其元素。

<input type="checkbox" name="X" id="myElement" />

<script>   document.getElementById('myElement').name = 'text'; </script>  

http://www.w3schools.com/JS/js_ex_dom.asp

http://www.w3schools.com/JS/js_ex_dom.asp