1

I want to validate my radio input by female and male value, how can I it? This in my code:

<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>
1
  • Please use a label element associated with each of your radio inputs via for/id attributes ("Associate Labels with Elements") (then an unstyled fieldset and a legend for Gender will be even better but first the labels ^^) Commented Nov 10, 2015 at 11:05

3 Answers 3

2

You can use the :checked selector and the length property to make sure an item was selected:

if (!$('input[name="gender"]:checked').length) {
    $('#e4').show(); // display the error div
}
Sign up to request clarification or add additional context in comments.

2 Comments

will .length not throw if nothing is selected? length of undefined...
No, the $() construct will always return an object, therefore it will always have a length property.
2

$(':radio').change(function() {
  if ($(this).is(':checked')) {
    $('#e4').hide()
  } else {
    $('#e4').show()
  }
})
<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>

Try this way

Comments

2

Following is the JSFiddle

Code

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

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

.hide{
    display:none;
}
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.