在java脚本或jquery中按名称获取radiobox检查值


Get radiobox checked value by name in java script or jquery

我正在开发一个应用程序,因为我需要在java脚本或jquery中按名称检查值。我的HTML代码是

 <input type="radio" name="type1" value="Manual"  /> Manual<br/>
 <input type="radio" name="type1" value="Auto"  /> Auto

我的javascript代码是

var aqi_type = (document.getElementsByName('type'+id).value)
alert(aqi_type);

https://i.stack.imgur.com/PUZwS.png

当我选中单选框时,我得到的值是未定义的。

建议我。

您可以使用属性等于选择器[name="value"]

$('input[type="radio"][name="type1"]:checked').val()

演示

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

演示更改事件

编辑

根据评论,您可以使用

var ids = 1;
$('input[type="radio"][name="type' + ids + '"]:checked').val()
if($('input[name="type1"]').prop('checked',true)){
  alert($(this).text());
}
<input type="radio" name="type1" value="Manual" id="radio1"  /> Manual<br/>

试试,

if (document.getElementById('radio1').checked) {
  aqi_type = document.getElementById('radio1').value;
}

这适用于IE8及以上版本和所有其他浏览器,

document.querySelector('input[name="type1"]:checked').value;

JQuery样式:

$('input[name="type1"]:checked').val();

您可以使用类似class="type1"的class属性来代替getElementsByName。所以html应该是:

<input type="radio" class="type1" value="Manual"  /> Manual<br/>
<input type="radio" class="type1" value="Auto"  /> Auto

和jquery:

var values = '';
for(var i = 0; i < $('.type1').length; i++){
   values += $('.type1').eq(i).val() + '|';
}
alert(values);

请试试这个!

这将处理所有单选按钮,而不考虑名称。

 $("input:radio").change("click", function () {
        if($(this).is(":checked"))
            alert($(this).val())
    })

你可以使用下面的行,这将得到所有的单选按钮以类型开始:

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