简体   繁体   English

无循环获取组中单选按钮的输入值

[英]Getting input value of a radio button in a group without loop

I need to obtain which radio button is checked using plain javascript ( No JQuery ) without looping through each input elements and checking for 'checked' attribute for each. 我需要获取使用普通javascript(否JQuery)检查哪个单选按钮,而不循环遍历每个输入元素并检查每个输入元素的“ checked”属性。

PS : Jquery solution would also be appreciated :) PS:jQuery解决方案也将不胜感激:)

Given HTML : 给定HTML:

      <tr id = "reportLayout">
         <th align="left" style="padding-right: 10px">Layout</th>
            <td>
             <input type="radio" name="layout" value="portrait">Portrait</input>                                                            
             <input type="radio" name="layout" value="landscape">Landscape</input>
            </td>
      </tr>

"PS : Jquery solution would also be appreciated :)" “ PS:Jquery解决方案也将不胜感激:)”

OK, use the :checked selector : OK,使用:checked选择器

var checkedRB = $('input[type="radio"][name="layout"]:checked');

Where the value of the checked radio would be: 所检查的无线电的值将为:

checkedRB.val();

To do it without jQuery the "standard" way to do it is with a loop, but you could also do this if you don't care about IE < 9: 要在没有jQuery的情况下执行此操作,“标准”方法是使用循环,但是如果您不关心IE <9,也可以执行此操作:

var checkedRB = document.querySelectorAll(
                     'input[type="radio"][name="layout"]:checked');
if (checkedRB.length === 0) {
    // none checked
} else {
    alert(checkedRB[0].value);
}

Demo: http://jsfiddle.net/xHAwX/1/ 演示: http//jsfiddle.net/xHAwX/1/

获取当前选中的单选按钮的

$("input[@name=radioname]:checked")

I guess you are only using radio boxes in reportLayout: 我猜您只在reportLayout中使用单选框:

$('#reportLayout').find(':checked')

will do it; 会做的;

var check = $('input[name:layout]:checked').val();
alert(check);

This will give you the value of currently checked radio button. 这将为您提供当前选中的单选按钮的值。

You can also check that if any radio button is checked or not by 您还可以通过以下方法检查是否选中了任何单选按钮:

var check = $("input[name:layout]:checked").length;
alert(check);

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

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