I've got the following form - 2 radio buttons in my A.php

<form action="form_processing.php" method="post" id ="myForm">
    <div class="radio-inline">
     <label>
      <input type="radio" name="direction" id="direction" value="up" checked>Up
     </label>
    </div>
    <div class="radio-inline">
     <label>
      <input type="radio" name="direction" id="direction" value="down" >Down
     </label>
    </div>
    <input type="hidden" name="status" value="false">   
    <br/>
    <button type="submit" name="sub" id="sub">Submit</button>
</form>

Then I've got the following jQuery A.js,

$('#myForm').on('submit', function(){
    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index, value){
        var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response){
            console.log(response);
        }
    });
    return false;
});

Then on my form_processing.php I've got,

<?php 
    print_r($_POST);
?>

When I monitor my console, no matter what I seem to do, I always end up getting...

Array
(
    [direction] => down
    [status] => false
)

I've spent 2 days trying to figure out but.. can't find the cause of the problem why values of the radios are not updated....

To be more specific - works on IE10/11, doesn't work on chrome (tried to clear the browsing data etc etc..still not working)

Can someone plz guide me on where I went wrong?

Thanks alot,

有帮助吗?

解决方案

The problem is that you are manually looping over all your inputs, regardless whether a radio button is checked or not. So when you are at the second radio button with the same name as the first, you overwrite your previous value.

You should probably let jQuery handle this by using:

data: $(this).serialize(),

You could of course manually check for the type of input and whether it is checked as well...

As I mentioned in my comment, you should only use an ID once per page as the ID has to be unique but that is not related to your problem.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top