Radio Button validation with jQuery
I have a jQuery validation on text field which is working fine but when I apply it on radio button then it don't work. I don't know where I'm wrong.
my HTML and jQuery code is,
<input type="text" placeholder="Name" name="name" id="name">
<input type="radio" name="gender" id="gender" value="1">
<input type="radio" name="gender" id="gender" value="2">
var name= jQuery('#name').val();
var gender= jQuery('#gender').val();
if(name.length == 0){
var error = true;
jQuery('#name_error').fadeIn(500);
}else{
jQuery('#name_error').fadeOut(500);
}
if(gender.value == 0){
var error = true;
jQuery('#gender_error').fadeIn(500);
}else{
jQuery('#gender_error').fadeOut(500);
}
Don't use same ID's
for multiple elements.
HTML:-
<input type="radio" name="gender" value="1">
<input type="radio" name="gender" value="2">
JS:-
$("input[name=gender]:checked").val()
because both of your radio button have the same id, Id must be unique. If you want to check radio button clicked or not then try:
$("input[name=gender]").is(":checked")
another thing one of radio button always be clicked so you dont need to validate it, but you need to check male or female.
to set default check:
<input type="radio" name="gender" class="gender" checked="checked" value="1">
You are using same ID
s multiple times. ID
s cannot be same. They must be unique.
Use prop()
to detect if radio button is checked or not. It returns boolean value.
JS:
$('#name_error,#gender_error').fadeOut();
var name = jQuery('#name').val();
if (name.length == 0) {
jQuery('#name_error').fadeIn(500);
}
if(!($("input[name='gender']").prop("checked"))){
$('#gender_error').fadeIn(500);
}
DEMO here.
链接地址: http://www.djcxy.com/p/88056.html下一篇: 使用jQuery进行单选按钮验证