检查radiobutton

时间:2017-10-23 12:07:17

标签: javascript radio-button

我试图在控制台上看到哪个单选按钮被选中。有两个单选按钮。我收到此错误TypeError:document.getElementById(...)为null我应该使用checked feauture而不是value?

<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">

<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">



var y=document.getElementById('edit-2').value;
if(y == 2)
{


console.log("no");

} else{
console.log("yes");


}

3 个答案:

答案 0 :(得分:0)

确保执行脚本时String sql=select * from PunchHistory whered punchDate like :date1; String date="2017-10-23"; List<PunchHistory> results =session.createQuery(StackperksConstants.sql) .setDate("date1", java.sql.Date.valueOf(date)) .list(); 字段存在。 否则,使用id="edit-2"函数,如:

document.ready

答案 1 :(得分:0)

似乎是这样的:

var y = document.getElementById('edit-2').checked;

if(y) {
  console.log("no");
} else{
  console.log("yes");
}
<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">

<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">

答案 2 :(得分:0)

当单选按钮不在表单中时,请使用checked代替value

var checkSelection = function () {
  if(document.getElementsByClassName('form-radio')[0].checked)
  {
    console.log("yes");
  } 
  else {
    console.log("no");
  }
}
<input required="required" class="form-radio" name="submitted[315]" type="radio"> Yes
<input required="required" class="form-radio" name="submitted[315]" type="radio" checked="checked"> No

<button onClick="checkSelection()">Check Selection</button>