1

im learning javascript, i got a radio button called gender, and its ID is male and female i try to validate to check wether it's checked or not, but it doesnt return any error message even the radio button is not checked here's my code

 var maleC=document.getElementById('male').value;
 var femaleC=document.getElementById('female').value;

 if(maleC.checked==false||femaleC.checked==false)
{
    document.getElementById('err5').innerHTML="Gender must be choosen";
}
 else
  {
   alert("proceed");
   {

why it's doesnt work? can u help me guys?

2
  • When are you checking this? What event? What is not working? Commented Jan 15, 2014 at 4:40
  • I checked this when i press submit button, the event that not working is checked condition inside if... Commented Jan 15, 2014 at 4:42

3 Answers 3

3

Should be

var maleC=document.getElementById('male');
var femaleC=document.getElementById('female');

 if(!(maleC.checked) || !(femaleC.checked))
{
    document.getElementById('err5').innerHTML="Gender must be choosen";
}

Ref: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

Sign up to request clarification or add additional context in comments.

3 Comments

what's the different beetween var maleC=document.getElementById('male'); and var maleC=document.getElementById('male').value;
maleC=document.getElementById('male').value; it get the value of the radio input
document.getElementById('male') reference to the element by its ID
0

While checking for checked property,use html element object, but here you are checking it on radio button value. Don't use .value

var maleC=document.getElementById('male'); // It will return you html element
 var femaleC=document.getElementById('female');

 if(!(maleC.checked)||!(femaleC.checked))
 {
    document.getElementById('err5').innerHTML="Gender must be choosen";
}
 else
  {
   alert("proceed");
   }

Comments

0

may be

 if($("input[name=demo-radio]:checked").val()=="male")
{
}
else if($("input[name=demo-radio]:checked").val()=="female")
{
}

else{
alert("gender must be chosen");
}

for js:

var x = document.getElementById("myCheck").checked;
if(x==true){}
else{alert("please select a gender")}

1 Comment

It's in jquery, while OP wants to know in javascript

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.