radio buttons post show value even none of the buttons are checked how to validate this?

StackOverflow https://stackoverflow.com/questions/18262432

  •  24-06-2022
  •  | 
  •  

Domanda

I have a registration form wich has a gender radio option showing male or female. in the HTML none are checked because i want the user to check one. like this:

<label class="radio">
    <input type="radio" name="gender" id="optionsRadios1" value="female">Female
</label>
<label class="radio">
    <input type="radio" name="gender" id="optionsRadios2" value="male">Male
</label>

I submit data trough jquery ajax. The strange thing is that the post of al inputs shows

[gender] => male if you submit the form with none of the 2 options checked

So how can i validate this if it never posts empty?

*I want to return a error if no option is selected so it forces a user to select a right gender..

È stato utile?

Soluzione

One really quick way of doing this is defaulting to a choice in the UI. This makes sure that the value is non-empty because you can't "uncheck" a radio button.

<input type="radio" name="gender" id="optionsRadios1" value="female" checked> Female

Edit:
Write your own submit function, and bind it to your submit button's onclick()

function submit() {
  if (!$("#optionsRadios1").prop("checked") && !$("#optionsRadios2").prop("checked")) {
    alert("please select a gender");
  }
  else {
    //Whatever you do to submit
  }
}

Altri suggerimenti

The following code will validate your form on the client side This validation will only allow the form to be submitted if one of the gender is selected. If none of the radio button is submitted then it will display an alert message and stop the form from redirecting to action.php.

<form name='whatever' onsubmit='return validate();' method='POST' action='action.php'>
    <label class="radio">
    <input type="radio" name="gender" id="optionsRadios1" onchange='validate()' value="female"> Female
    </label>
    <label class="radio">
    <input type="radio" name="gender" id="optionsRadios2" onchange='validate()' value="male"> Male
    </label>
    <input type='submit' value='submit'>
</form>

<script type='text/javascript'>
    function validate(){
    var feObj=document.getElementById("optionsRadios1");
    var maleObj=document.getElementById("optionsRadios2");
    if (feObj.checked){
        return true;
    }
    if (maleObj.checked){
        return true;
    }
    alert ("Please select a gender");
    return false;
    }   
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top