Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio not serializing with serializeArray

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?

like image 755
Cole Avatar asked Feb 10 '13 02:02

Cole


2 Answers

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

like image 149
nice ass Avatar answered Oct 11 '22 01:10

nice ass


<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!

like image 35
Purple Tentacle Avatar answered Oct 11 '22 03:10

Purple Tentacle