-3
<form>
    <input id="gen" name="gender" type="radio"> Male 
    <br>
    <input id="gen1" name="gender" type="radio"> Female
</form>

function formValidate() {
  if((gen.checked==false)&&(gen1.checked==false)) {
    alert("please select a gender");
    return false;
  }
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • I would change your if condition to check with ```===``` instead of ```==```. Read more [here](https://stackoverflow.com/questions/523643/difference-between-and-in-javascript) – tomerpacific Jun 30 '19 at 09:38
  • Is this all your JS code? There is nothing calling `formValidate`. Also where do you define `gen` & `gen1`? – Nick Parsons Jun 30 '19 at 09:40

3 Answers3

1

You can try checking the checked property like the following way:

function formValidate(e) {
  var chkEl = document.querySelector('[name=gender]:checked');
  if(chkEl == null){
    alert("please select a gender");
    e.preventDefault();
  }
}
<form>
  <input type="radio" name="gender" value="Male">Male
  <input type="radio" name="gender" value="Female">Female
  <button onclick="formValidate(event)">Click</button>
<form>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • Thank you. i have a question why you have passed a parameter in function i am really confused about parameter or arguments especially here in this gender validation program. – Manish Pandey Jun 30 '19 at 12:14
  • @ManishPandey, `event` has been passed to the function. Inside the function that event (`submit`) is neutralized based on the condition:) – Mamun Jun 30 '19 at 12:17
0
<form onsubmit="return formValidate()">
  <input id="gen" name="gender" type="radio"> Male 
  <br>
  <input id="gen1" name="gender" type="radio"> Female
</form>

 function formValidate() {
 if((gen.checked==false)&&(gen1.checked==false)) {
   alert("please select a gender");
   return false;
 }
}

You need to call the function while submitting the function, then validation will happen You can use jQuery click Function to validate the fields.

Samson
  • 352
  • 1
  • 11
0

You can set onsubmit="return formValidate()" property and that will called when the client click Submit button

function formValidate() {
  if((gen.checked==false)&&(gen1.checked==false)) {
    alert("please select a gender");
    return false;
  }
  else
    return true;
}
<form onsubmit="return formValidate()">
    <input id="gen" name="gender" type="radio"> Male 
    <br/>
    <input id="gen1" name="gender" type="radio"> Female
    <br/>
    <input type="submit" value="Submit">
</form>
barzin.A
  • 1,554
  • 2
  • 12
  • 20