jquery中的无线电输入验证

时间:2015-11-10 07:48:56

标签: javascript jquery html css3

我想通过女性和男性价值验证我的收音机输入,我该怎么办? 这在我的代码中:

<span>Gender:</span>
<input type="radio"  name="gender" id="male" />Male
<input type="radio"  name="gender" id="female" />Female
<div id="e4" class="error2">Please choose your gender</div>

3 个答案:

答案 0 :(得分:2)

您可以使用:checked选择器和length属性来确保选择了某个项目:

if (!$('input[name="gender"]:checked').length) {
    $('#e4').show(); // display the error div
}

答案 1 :(得分:2)

&#13;
&#13;
$(':radio').change(function() {
  if ($(this).is(':checked')) {
    $('#e4').hide()
  } else {
    $('#e4').show()
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span>Gender:</span>
<input type="radio" name="gender" id="male" value="Male" />Male
<input type="radio" name="gender" id="female" value="Female" />Female
<div id="e4" class="error2">Please choose your gender</div>
&#13;
&#13;
&#13;

试试这种方式

答案 2 :(得分:2)

以下是JSFiddle

代码

&#13;
&#13;
function validate(){
	var value = $('input[name="gender"]:checked').val();
    if(!value){
    	$("#e4").fadeIn()
    }
}

$("input[name='gender']").on("change", function(){
	$("#e4").fadeOut()
})
&#13;
.error2{
    color:red;
}

.hide{
    display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span>Gender:</span>
<input type="radio"  name="gender" id="male" />Male
<input type="radio"  name="gender" id="female" />Female
<div id="e4" class="error2 hide">Please choose your gender</div><br/>
<button onclick="validate()">Validate</button>
&#13;
&#13;
&#13;