Javascript - 如果没有选择单选按钮,请检查第一个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22300382/
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-10-27 22:52:44  来源:igfitidea点击:

Javascript - If no radio buttons are selected, check the first one

javascriptradiochecked

提问by MichaelHasfel

I'm a beginner in JavaScript. I have several radio buttons on my dynamic page and I want to create a script to make the following:

我是 JavaScript 的初学者。我的动态页面上有几个单选按钮,我想创建一个脚本来进行以下操作:

HTML:

HTML:

    <input type="radio" id="elemainfoto">
    <input type="radio" id="elemainfoto">
    <input type="radio" id="elemainfoto">

JavaScript:

JavaScript:

    var radio = '#elemainfoto',
    if(radd.value == 0) {
        radd.checked the first radio element,
    } else {
        keep the way it is,
    }

If none of the radio elements are marked, mark the first compulsory.

如果没有标记无线电元素,则标记第一个必填项。

回答by Danielito

I your expectation is that the first item get selected by default, then you should use HTML and not javascript for that and please note that you should not use two HTML elements with the same id in your case you should either replace by a class and/or add unique Ids for elements.

我的期望是默认选择第一个项目,然后你应该使用 HTML 而不是 javascript,请注意你不应该使用两个具有相同 id 的 HTML 元素,你应该用一个类替换和/或为元素添加唯一 ID。

<input type="radio" class="elemainfoto" id="item1" checked>
<input type="radio" class="elemainfoto" id="item2">
<input type="radio" class="elemainfoto" id="item3>

Updated the answer based on RobG comment.

根据 RobG 评论更新了答案。

回答by dfsq

Something like this in pure JS (I changed ids to classes id should be unique):

纯 JS 中的类似内容(我将 id 更改为类 id 应该是唯一的):

var radio = document.querySelectorAll('.elemainfoto'),
    checked = false;

for (var i = 0; i < radio.length; i++) {
    if (radio[i].checked) {
        checked = true;
        break;
    }
}

if (!checked) {
    radio[0].checked = true;
}
else {
    alert('something is checked')
}

A little shorter with jQuery:

使用 jQuery 稍微短一点:

var $radio = $('.elemainfoto');

if (!$radio.filter(':checked').length) {
    $radio[0].checked = true;
}
else {
    alert('something is checked')
}

回答by Jentel

using 'id' attribute in html with the same value more than once is invalid, you should use "name" for an input.

在 html 中多次使用具有相同值的 'id' 属性是无效的,您应该使用“name”作为输入。

HTML:

HTML:

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

JavaScript:

JavaScript:

 var radio = document.getElementsByName('elementinfoto'); // get all radio buttons
 var isChecked = 0; // default is 0 
 for(var i=0; i<radio.length;i++) { // go over all the radio buttons with name 'elementinfoto'
   if(radio[i].checked) isChecked = 1; // if one of them is checked - tell me
 }

 if(isChecked == 0) // if the default value stayed the same, check the first radio button
   radio[0].checked = "checked";

example: http://jsfiddle.net/yxm4N/2/

示例:http: //jsfiddle.net/yxm4N/2/

回答by RobG

A radio button group is formed by giving radio buttons the same name. An ID is optional and usually not necessary. If an ID is provided, each should have a different value. And the buttons should have a value so that there's a point to their existence.

单选按钮组是通过给单选按钮相同的名称形成的。ID 是可选的,通常不是必需的。如果提供了 ID,则每个 ID 都应具有不同的值。按钮应该有一个值,这样它们的存在就有了意义。

To have one button selected by default, simply set the chosen button's checkedattribute:

要默认选择一个按钮,只需设置所选按钮的选中属性:

<form id="foo">
  <input type="radio" name="elemainfoto" valu="0" checked>0<br>
  <input type="radio" name="elemainfoto" valu="1">1<br>
  <input type="radio" name="elemainfoto" valu="2">2<br>
  <input type="reset">
</form>

Now if no other button is selected, or the form is reset, one button will be selected. Note that if you do not set a button as the default selected, then once a user checks a button, the only way to deselect it is to select a different radio button in the same group, or use a reset button (if provided).

现在,如果没有选择其他按钮,或者表单被重置,则将选择一个按钮。请注意,如果您没有将按钮设置为默认选择,那么一旦用户选中一个按钮,取消选择它的唯一方法是在同一组中选择不同的单选按钮,或使用重置按钮(如果提供)。

If you want to set the default checked button in script, there are a couple of options. One is:

如果要在脚本中设置默认选中按钮,有几个选项。一种是:

var buttons = document.getElementsByName('elemainfoto');
buttons[0].defaultChecked = true;

If you really want to check if one is selected, add a button like the following to the form:

如果您真的想检查是否选择了一个,请在表单中添加如下所示的按钮:

  <input type="button" value="Check buttons" onclick="checkButtons(this);">

Then the checkButtonsfunction can be:

然后checkButtons函数可以是:

function checkButtons(el) {
  var buttons;
  var form = el && el.form;

  if (form) {
    buttons = form.elemainfoto;

    for (var i=0, iLen=buttons.length; i<iLen; i++) {

      // If a button is checked, return its value
      if (buttons[i].checked) {
        return buttons[i].value;
      }
    }
  }
  // Otherwise, try to check the first one and return undefined
  buttons && buttons[0].checked;
}

回答by CJ Ramki

you need to know how to use radio element. Id is unique in html page. you should assign same name for each radio element.

你需要知道如何使用无线电元素。id 在 html 页面中是唯一的。您应该为每个无线电元素分配相同的名称。

<input type="radio" name="elemainfoto" id="first" value="1" />
element 1
<input type="radio" name="elemainfoto" id="second" value="2" />
element 2
<input type="radio" name="elemainfotor" id="thrid" value="3" /> 
element 3

if you want to check the first radio button as default, set it in input tag attribute.

如果您想默认选中第一个单选按钮,请将其设置在输入标签属性中。

<input type="radio" name="elemainfoto" id="first" value="1" checked="true"/>
    element 1

or you can do it with javascript also,

或者你也可以用javascript来做,

$("input:radio[name=elemainfoto]:first").attr('checked', true);

you can perform action for each radio button click, to know which item is checked

您可以为每个单选按钮单击执行操作,以了解检查了哪个项目

$(function(){
  $('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      alert($(this).val());
    }
  });
});

if you want to perform a separate action for each radio button, try this below code

如果您想为每个单选按钮执行单独的操作,请尝试以下代码

$(function () {
    $('input[type="radio"]').click(function () {
        if ($(this).is(':checked')) {
            if ($(this).val() == '1') alert('first radio element is checked');
            if ($(this).val() == '2') alert('second radio element is checked');
            if ($(this).val() == '3') alert('third radio element is checked');
        }
    });
});

SEE THIS FIDDLE DEMO

看这个小提琴演示