phphtmlformsradio-button

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


I have a registration form which 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 through jQuery ajax. The strange thing is that the post of all 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.


Solution

  • 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
      }
    }