Will Bainbridge
Will Bainbridge

Reputation: 73

How can I get the value of radio buttons with jQuery?

My current code gets all the data from a form then outputs it to the console as an Array (I'm testing a contact form). All the data it returns is correct but the value of the radio button is always the same.

html:

<form class="form1" action="form.php" method="post">
<div class="form-sect">
    <div class="formb-check">
        <input type="text" name="name" placeholder="Name" class="formb-small">
        <input type="text" name="id" placeholder="ID: 00000000" class="formb-small">
    </div>
</div>
<div class="form-sect">
    <div class="formb-srv">
        <div class="formb-check">
            <input type="radio" name="server" id="server-1" value="Srv 1"><label for="server-1">Server 1</label>
            <input type="radio" name="server" id="server-2" value="Srv 2"><label for="server-2">Server 2</label>
        </div>
    </div>
</div>
<div>
    <div>
        <textarea name="message" placeholder="Message....."></textarea>
        <button type="submit" name="submit">Submit Report</button>
    </div>
</div>

jQuery:

$('form.form1').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; });

PHP:

<?php 
if(isset($_POST['name'], $_POST['id'], $_POST['server'], $_POST['message'])){
    print_r($_POST);
} ?>

In the array I'm using for testing the value of the radio button is always the second value used, in this code it is Srv 2. Like this: [server] => Srv 2

Upvotes: 1

Views: 439

Answers (3)

Bram Verstraten
Bram Verstraten

Reputation: 1557

You should serialize the form like this:

$('form.form1').on('submit', function(event) {
    event.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        success: function (response) {
            console.log(response);
        }
    });
});

Upvotes: 3

Jon P
Jon P

Reputation: 19797

You need to check for "checked" on radio buttons (and check boxes)

that.find('[name]').each(function(index, value) {    
    var name = $(this).attr('name');
    var notCheckOrRadio = !$(this).is('[type=radio],[type=checkbox]') ;
    if( notCheckOrRadio || $(this).is(':checked')) {
       data[name] = $(this).val();
    }
});

Note, while this answers the question as asked, you should us Bram's updated approach.

Upvotes: 1

Soubhagya Kumar Barik
Soubhagya Kumar Barik

Reputation: 2615

Every time you are getting server 2 because in jquery $.each will replace second value with first one.

N:B - Don't use $.each in this case and be specific because later if new fields will come then it will be problem example checkboxes and all.

N:B- Don't use return false always use e.preventDefault();

You need to check checked radio button. Remove the unnecessary lines of code. Please follow the below example

   $('form.form1').on('submit', function(e) {
            e.preventDefault();
            data = {'name':$('[name="name"]').val(),'id':$('[name="id"]').val(),'server':$('[name="server"]:checked').val(),'message':$('[name="message"]').val()};
            $.ajax({
                url: 'form.php',
                type: 'POST',
                dataType:'json',
                data: data,
                success: function(response){
                    console.log(response);
                }
            });
        });

Upvotes: 0

Related Questions