我想通过女性和男性价值验证我的收音机输入,我该怎么办? 这在我的代码中:
<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>
答案 0 :(得分:2)
您可以使用:checked
选择器和length
属性来确保选择了某个项目:
if (!$('input[name="gender"]:checked').length) {
$('#e4').show(); // display the error div
}
答案 1 :(得分:2)
$(':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;
试试这种方式
答案 2 :(得分:2)
以下是JSFiddle
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;