index.php:
<form id = "regform" action = "registration.php" method = "POST">
<label id = "namelabel">Username: </label> <input type = "text" name = "username" class = "username" maxlength = "40" placeholder = "Enter a Username"><br>
<label id = "namelabel">Password: </label> <input type = "password" class = "password" name = "password" placeholder = "Enter Password"><br>
<label id = "namelabel">Gender: </label>
<input type="radio" name="gender" value = "Male"> Male
<input type="radio" name="gender" value = "Female"> Female
<label id = "namelabel">Email: </label> <input type = "text" name = "email" class = "email" placeholder = "Enter your Email"><br>
<a href="#" title="Register" id = "register" style = "margin-left:25px;">Register</a>
</form>
$("#register").click(function () {
$.post($('#regform').attr("action"), $('#regform').serializeArray(), function (data) {
if (data == 'checkradio') {
$('#regmsg').html('Please choose a gender.');
}
});
});
Server side:
$required_fields = array('username','password','gender','email');
foreach($_POST as $key =>$value) {
if(empty($value) && in_array($key, $required_fields) === true){
echo 'checkradio';
}
}
It serializes everything except the Radio buttons. What is the problem?
As @undefined told you, unchecked checkboxes and radios are not sent.
If you don't want a default checked state for your gender field, then add a hidden input field with the same name and empty value before the radios:
<input type="hidden" name="gender" value="" />
Forms are processed sequentially, so if the radio is checked, its value will override the hidden input value
<input type="radio" name="gender" value="" style="display:none;" checked>
Add an extra radio option like this, the value will be nothing and it will not show to the user.
Updated to add 'checked' as suggested by @Larzan. Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With