Domanda

I'm facing a strange error which I cannot figure out. I have a form that submits a set of 2 radio buttons 1 male other female like this:

<label class="radio">
    <input type="radio" name="gender" id="femaleRadio" value="f">
    Vrouw
</label>
<label class="radio">
    <input type="radio" name="gender" id="maleRadio" value="m">
    Man
</label>

Through jQuery AJAX I send it to php... but when I echo the post it always shows that male is selected. Even if I selected the female. Why is this?

$gender = strip_tags(trim($_POST['gender']));
echo $gender; exit;

I always get M. If I remove the male option in HTML, I get F. This must have a simple solution but I cannot find it.

here is the piece of javascript where i get all the data from the form

var el = $(this),

url = el.attr('action'),
type = el.attr('method'),

data = {}

// The loop to get al form data
el.find('[name]').each(function(index, value) {

    var el = $(this)
    name = el.attr('name'),
    value = el.val();

    //make data object
    data[name] = value;

});

validation of radio buttons on submit

//Do some client side validation first
if (!$("#femaleRadio").prop("checked") && !$("#maleRadio").prop("checked")) {

    //Check if radio button is selected
    $('#regError').html("<strong>Fout: </strong> Selecteer een geslacht");
    $('#regError').fadeIn();
    return false;
}
È stato utile?

Soluzione

In this we need to know how radio button works.

All radio buttons in a single group will share same name.

In your case - gender.

So, when we select any one option and submit the form, then only the selected radio button's value is stored in the gender.

But as per the JavaScript/jQuery code you wrote, you are simply taking the value of each element and take it as the value for it's name.

In this case, you are not checking whether any radio button is selected or not.

You can try following code

data['gender'] = $('[name=gender]:checked').val();

If nothing is selected - the gender property will be undefined.

You can change this logic as needed.

From the code it seems, you are iterating on all available field names. In that case you can update that like this

// The loop to get al form data
el.find('[name]').each(function(index, value) {

    var el = $(this)
    name = el.attr('name'),
    value = el.val();

    //make data object
    data[name] = value;

    //If this element is a radio button
    if($(this).is(':radio')) {
        data[name] = $('[name=' + name + ']:checked').val();
    }

});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top