如何验证单选按钮

时间:2015-02-27 06:24:56

标签: javascript

我试图通过单选按钮验证性别。这是我的代码。但它不起作用。 的JavaScript

function checkgender() {
  var gen = document.subscribe.gender[0].checked;
  var gen1 = document.subscribe.gender[1].checked;

  if((gen==false)&&(gen1==false)) {

    alert('Please Select your Gender Type!');
    return false;
  }
  return true;
}

html

<input type="radio" name="gender" value="male" id="gender">male
<input type="radio" name="gender" value="female" id="gender">female
<input name="but" type="button" value="Add" class="btn btn-primary" onClick="checkgender()" /> 

5 个答案:

答案 0 :(得分:0)

<强> HTML

<input name="but" type="button" value="Add" class="btn btn-primary"/>

<强>脚本:

$(".btn").click(function(){
   var gen = document.subscribe.gender[0].checked;
   var gen1 = document.subscribe.gender[1].checked;

   if((gen==false)&&(gen1==false))
   {
     <!--document.getElementById("fn6").style.borderColor = "#ED291F";-->
     alert('Please Select your Gender Type!');
   }
});

答案 1 :(得分:0)

var gen = document.subscribe.gender[0].checked; var gen1 = document.subscribe.gender[1].checked;

而不是使用

var x = document.getElementById(“gender1”)。value;
var x = document.getElementById(“gender2”)。value;

HTML

<input type="radio" name="gender" value="male" id="gender1">
<input type="radio" name="gender" value="female" id="gender2">

或者完整的例子 访问

http://www.chennaisunday.com/jsradio.html

答案 2 :(得分:0)

最后我找到了一个解决方案。谢谢您的支持

function checkgender()
     {
var gen = document.getElementsByName('gender');
var ischecked = false;
for ( var i = 0; i < gen.length; i++) {
    if(gen[i].checked) {
        ischecked = true;
        return true;
        break;
    }
}
if(!ischecked)   { 
    alert("Please Select your Gender Type");
    return false;
}
}

答案 3 :(得分:0)

<强> HTML

<input type="radio" name="gender" value="male" id="rdbMale">male
<input type="radio" name="gender" value="female" id="rdbFemale">female
<input name="but" id="btnGender" type="button" value="Add" class="btn btn-rimary"/>

<强>脚本

$("#btnGender").click(function(){

  if(!$('#rdbMale').is(':checked') && !$('#rdbFemale').is(':checked'))
  {
    alert('Please Select your Gender Type!');
  }

});

答案 4 :(得分:-1)

检查您的onclick事件

<input name="but" type="button" value="Add" class="btn btn-primary" onClick="javascript:checkgender();" />