简体   繁体   English

如何检查是否使用 JavaScript 选择了单选按钮?

[英]How can I check whether a radio button is selected with JavaScript?

I have two radio buttons within an HTML form.我在 HTML 表单中有两个单选按钮。 A dialog box appears when one of the fields is null.当其中一个字段为空时,会出现一个对话框。 How can I check whether a radio button is selected?如何检查是否选择了单选按钮?

Let's pretend you have HTML like this假设你有这样的 HTML

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

For client-side validation, here's some Javascript to check which one is selected:对于客户端验证,这里有一些 Javascript 来检查选择了哪一个:

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.根据您的标记的确切性质,上述内容可能会更有效,但这应该足以让您入门。


If you're just looking to see if any radio button is selected anywhere on the page, PrototypeJS makes it very easy.如果您只是想查看是否在页面上的任何位置选择了任何单选按钮, PrototypeJS可以很容易地做到这一点。

Here's a function that will return true if at least one radio button is selected somewhere on the page.如果在页面某处至少选择了一个单选按钮,此函数将返回 true。 Again, this might need to be tweaked depending on your specific HTML.同样,这可能需要根据您的特定 HTML 进行调整。

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}

For server-side validation (remember, you can't depend entirely on Javascript for validation!) , it would depend on your language of choice, but you'd but checking the gender value of the request string.对于服务器端验证(请记住,您不能完全依赖 Javascript 进行验证!) ,这取决于您选择的语言,但您只需要检查请求字符串的gender值。

With jQuery , it'd be something like使用jQuery ,它就像

if ($('input[name=gender]:checked').length > 0) {
    // do something here
}

Let me break that down into pieces to cover it more clearly.让我把它分解成碎片以更清楚地覆盖它。 jQuery processes things from left to right. jQuery 从左到右处理事物。

input[name=gender]:checked
  1. input limits it to input tags. input将其限制为输入标签。
  2. [name=gender] limits it to tags with the name gender within the previous group. [name=gender]将其限制为上一组中名称为性别的标签。
  3. :checked limits it to checkboxes/radio buttons that are selected within the previous group. :checked将其限制为在前一组中选择的复选框/单选按钮。

If you want to avoid this altogether, mark one of the radio buttons as checked ( checked="checked" ) in the HTML code, which would guarantee that one radio button is always selected.如果您想完全避免这种情况,请在 HTML 代码中将其中一个单选按钮标记为选中 ( checked="checked" ),这样可以保证始终选中一个单选按钮。

A vanilla JavaScript way一种普通的 JavaScript 方式

var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
    if (radios[i].type === 'radio' && radios[i].checked) {
        // get value, set checked flag or do whatever you need to
        value = radios[i].value;       
    }
}

You can use this simple script.您可以使用这个简单的脚本。 You may have multiple radio buttons with same names and different values.您可能有多个具有相同名称和不同值的单选按钮

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

Just trying to improve on Russ Cam's solution with some CSS selector sugar thrown in with the vanilla JavaScript.只是试图通过一些 CSS 选择器糖来改进Russ Cam 的解决方案,并在 vanilla JavaScript 中加入。

var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;

No real need for jQuery here, querySelectorAll is widely supported enough now.这里不需要 jQuery,querySelectorAll 现在得到了足够广泛的支持。

Edit: fixed a bug with the css selector, I've included the quotes, although you can omit them, in some cases you can't so it's better to leave them in.编辑:修复了css选择器的一个错误,我已经包含了引号,虽然你可以省略它们,在某些情况下你不能,所以最好把它们留在里面。

HTML Code HTML 代码

<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >

Javascript Code: Javascript代码:

var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
    if(off_payment_method[i].checked) {
        ischecked_method = true;
        break;
    }
}
if(!ischecked_method)   { //payment method button is not checked
    alert("Please choose Offline Payment Method");
}

The scripts in this page helped me come up with the script below, which I think is more complete and universal.这个页面中的脚本帮助我想出了下面的脚本,我认为它更完整和通用。 Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form.基本上,它将验证表单中任意数量的单选按钮,这意味着它将确保已为表单中的每个不同单选组选择了单选选项。 eg in the test form below:例如在下面的测试表格中:

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. RadioValidator 脚本将确保在提交之前已经为“test1”和“test2”给出了答案。 You can have as many radio groups in the form, and it will ignore any other form elements.您可以在表单中拥有尽可能多的单选组,它会忽略任何其他表单元素。 All missing radio answers will show inside a single alert popup.所有缺少的无线电答案都将显示在一个警报弹出窗口中。 Here it goes, I hope it helps people.就这样吧,希望对大家有所帮助。 Any bug fixings or helpful modifications welcome :)欢迎任何错误修复或有用的修改:)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

With mootools ( http://mootools.net/docs/core/Element/Element )使用 mootools ( http://mootools.net/docs/core/Element/Element )

html: html:

<input type="radio" name="radiosname" value="1" />
<input type="radio" name="radiosname" value="2" id="radiowithval2"/>
<input type="radio" name="radiosname" value="3" />

js: js:

// Check if second radio is selected (by id)
if ($('radiowithval2').get("checked"))

// Check if third radio is selected (by name and value)
if ($$('input[name=radiosname][value=3]:checked').length == 1)


// Check if something in radio group is choosen
if ($$('input[name=radiosname]:checked').length > 0)


// Set second button selected (by id)
$("radiowithval2").set("checked", true)

Note this behavior wit jQuery when getting radio input values:在获取无线电输入值时,请注意 jQuery 的这种行为:

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.所以$('input[name="myRadio"]').val()不会像您预期的那样返回单选输入的检查值——它返回第一个单选按钮的值。

I used spread operator and some to check least one element in the array passes the test.我使用了扩展运算符一些来检查数组中的至少一个元素是否通过了测试。

I share for whom concern.我为谁担忧。

 var checked = [...document.getElementsByName("gender")].some(c=>c.checked); console.log(checked);
 <input type="radio" name="gender" checked value="Male" /> Male <input type="radio" name="gender" value="Female" / > Female

There is very sophisticated way you can validate whether any of the radio buttons are checked with ECMA6 and method .some() .有一种非常复杂的方法可以验证是否使用 ECMA6 和方法.some()检查了任何单选按钮。

Html: html:

<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />

And javascript:和 javascript:

let htmlNodes = document.getElementsByName('status');

let radioButtonsArray = Array.from(htmlNodes);

let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);

isAnyRadioButtonChecked will be true if some of the radio buttons are checked and false if neither of them are checked.如果某些单选按钮被选中, isAnyRadioButtonChecked将为true ,如果它们都未选中,则为false

返回单选按钮中的所有选中元素

  Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);

this is a utility function I've created to solve this problem这是我为解决此问题而创建的实用程序功能

    //define radio buttons, each with a common 'name' and distinct 'id'. 
    //       eg- <input type="radio" name="storageGroup" id="localStorage">
    //           <input type="radio" name="storageGroup" id="sessionStorage">
    //param-sGroupName: 'name' of the group. eg- "storageGroup"
    //return: 'id' of the checked radioButton. eg- "localStorage"
    //return: can be 'undefined'- be sure to check for that
    function checkedRadioBtn(sGroupName)
    {   
        var group = document.getElementsByName(sGroupName);

        for ( var i = 0; i < group.length; i++) {
            if (group.item(i).checked) {
                return group.item(i).id;
            } else if (group[0].type !== 'radio') {
                //if you find any in the group not a radio button return null
                return null;
            }
        }
    }

This would be valid for radio buttons sharing the same name, no JQuery needed.这对于共享相同名称的单选按钮有效,不需要 JQuery。

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];

If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:如果我们正在谈论复选框并且我们想要一个列表,其中选中的复选框共享一个名称:

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)

With JQuery, another way to check the current status of the radio buttons is to get the attribute 'checked'.使用 JQuery,检查单选按钮当前状态的另一种方法是获取“已检查”属性。

For Example:例如:

<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />

In this case you can check the buttons using:在这种情况下,您可以使用以下命令检查按钮:

if ($("#gender_male").attr("checked") == true) {
...
}

just a lil bit modification to Mark Biek ;只是对 Mark Biek 稍作修改;

HTML CODE代码

<form name="frm1" action="" method="post">
  <input type="radio" name="gender" id="gender_Male" value="Male" />
  <input type="radio" name="gender" id="gender_Female" value="Female" / >
  <input type="button" value="test"  onclick="check1();"/>
</form>

and Javascript code to check if radio button is selected和 Javascript 代码检查单选按钮是否被选中

<script type="text/javascript">
    function check1() {            
        var radio_check_val = "";
        for (i = 0; i < document.getElementsByName('gender').length; i++) {
            if (document.getElementsByName('gender')[i].checked) {
                alert("this radio button was clicked: " + document.getElementsByName('gender')[i].value);
                radio_check_val = document.getElementsByName('gender')[i].value;        
            }        
        }
        if (radio_check_val === "")
        {
            alert("please select radio button");
        }        
    }
</script>

http://www.somacon.com/p143.php/ http://www.somacon.com/p143.php/

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

This code will alert the selected radio button when the form is submitted.提交表单时,此代码将提醒选定的单选按钮。 It used jQuery to get the selected value.它使用 jQuery 来获取选定的值。

 $("form").submit(function(e) { e.preventDefault(); $this = $(this); var value = $this.find('input:radio[name=COLOR]:checked').val(); alert(value); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input name="COLOR" id="Rojo" type="radio" value="red"> <input name="COLOR" id="Azul" type="radio" value="blue"> <input name="COLOR" id="Amarillo" type="radio" value="yellow"> <br> <input type="submit" value="Submit"> </form>

HTML: HTML:

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

JAVAScript: JAVA脚本:

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        return false;
}

So basically, what this code does is to loop through a nodeList that contains all the input elements.所以基本上,这段代码的作用是遍历一个包含所有输入元素的 nodeList。 In case one of these input elements is of type radio and is checked then do something and break the loop.如果这些输入元素之一是radio类型并且被检查然后做一些事情并打破循环。

If the loop doesn't detect an input element been selected, the boolean variable selected will stay false , and applying a conditional statement we can execute something for this case.如果循环没有检测到输入元素被选中,则布尔变量selected将保持为false ,并且应用条件语句我们可以针对这种情况执行一些操作。

 let inputs = document.querySelectorAll('input') let btn = document.getElementById('btn') let selected = false function check(){ for(const input of inputs){ if(input.type === 'radio' && input.checked){ console.log(`selected: ${input.value}`) selected = true break } } if(!selected) console.log(`no selection`) } btn.addEventListener('click', check)
 <input type="radio" name="option" value="one"> <label>one</label> <br> <input type="radio" name="option" value="two"> <label>two</label> <br> <br> <button id="btn">check selection</button>

Here is the solution which is expanded upon to not go ahead with submission and send an alert if the radio buttons are not checked.这是扩展为不继续提交并在未选中单选按钮时发送警报的解决方案。 Of course this would mean you have to have them unchecked to begin with!当然,这意味着您必须一开始就取消选中它们!

if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
  alert ("You must select a button");
  return false;
}

Just remember to set the id ('radio1','radio2' or whatever you called it) in the form for each of the radio buttons or the script will not work.只需记住在表单中为每个单选按钮设置 id('radio1'、'radio2' 或其他任何名称),否则脚本将不起作用。

An example:一个例子:

if (!checkRadioArray(document.ExamEntry.level)) { 
    msg+="What is your level of entry? \n"; 
    document.getElementById('entry').style.color="red"; 
    result = false; 
} 

if(msg==""){ 
    return result;  
} 
else{ 
    alert(msg) 
    return result;
} 

function Radio() { 
    var level = radio.value; 
    alert("Your level is: " + level + " \nIf this is not the level your taking then please choose another.") 
} 

function checkRadioArray(radioButtons) { 
    for(var r=0;r < radioButtons.length; r++) { 
        if (radioButtons[r].checked) { 
            return true; 
        } 
    } 
    return false; 
} 

The form表格

<form name="teenageMutant">
  <input type="radio" name="ninjaTurtles"/>
</form>

The script剧本

if(!document.teenageMutant.ninjaTurtles.checked){
  alert('get down');
}

The fiddle: http://jsfiddle.net/PNpUS/小提琴:http: //jsfiddle.net/PNpUS/

I just want to ensure something gets selected (using jQuery):我只是想确保某些东西被选中(使用 jQuery):

// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female

// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
    alert("Please select your gender.");
    return false;
}

If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers , the following functional approach is a little more tasteful to me than a for loop:如果你想要 vanilla JavaScript,不想通过在每个单选按钮上添加 ID 来弄乱你的标记,并且只关心现代浏览器,那么下面的函数方法对我来说比 for 循环更有品味:

<form id="myForm">
<label>Who will be left?
  <label><input type="radio" name="output" value="knight" />Kurgan</label>
  <label><input type="radio" name="output" value="highlander" checked />Connor</label>
</label>
</form>

<script>
function getSelectedRadioValue (formElement, radioName) {
    return ([].slice.call(formElement[radioName]).filter(function (radio) {
        return radio.checked;
    }).pop() || {}).value;
}

var formEl = document.getElementById('myForm');
alert(
   getSelectedRadioValue(formEl, 'output') // 'highlander'
)
</script>

If neither is checked, it will return undefined (though you could change the line above to return something else, eg, to get false returned, you could change the relevant line above to: }).pop() || {value:false}).value;如果两者都未选中,它将返回undefined (尽管您可以更改上面的行以返回其他内容,例如,要返回false ,您可以将上面的相关行更改为: }).pop() || {value:false}).value; }).pop() || {value:false}).value; ). )。

There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a value property on the list of form child radio elements (found in the above code as formElement[radioName] ), but that has its own problems: How to polyfill RadioNodeList?还有一种前瞻性的 polyfill 方法,因为RadioNodeList接口应该可以很容易地在表单子单选元素列表上使用value属性(在上面的代码中为formElement[radioName] ),但这有其自身的问题: 如何填充 RadioNodeList?

This is also working, avoiding to call for an element id but calling it using as an array element.这也有效,避免调用元素 id,但将其作为数组元素调用。

The following code is based on the fact that an array, named as the radiobuttons group, is composed by radiobuttons elements in the same order as they where declared in the html document:以下代码基于这样一个事实,即名为 radiobuttons 组的数组由 radiobuttons 元素组成,其顺序与它们在 html 文档中声明的顺序相同:

if(!document.yourformname.yourradioname[0].checked 
   && !document.yourformname.yourradioname[1].checked){
    alert('is this working for all?');
    return false;
}

Try尝试

[...myForm.sex].filter(r=>r.checked)[0].value

 function check() { let v= ([...myForm.sex].filter(r=>r.checked)[0] || {}).value ; console.log(v); }
 <form id="myForm"> <input name="sex" type="radio" value="men"> Men <input name="sex" type="radio" value="woman"> Woman </form> <br><button onClick="check()">Check</button>

Give radio buttons, same name but different IDs.提供单选按钮,名称相同但 ID 不同。

var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
  //condition
  final_answer = verified1;
}
else
{
  if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
    //condition
    final_answer = verified2;
   }
   else
   {
     return false;
   }
}

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

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