Using jQuery to send the value of a radio button to a PHP script

I’ve googled this extensively, but haven’t found anything that quite answers my need.

I would like to be able to capture both the id and the value of a radio button when it is sent to a PHP script. Of course, the value is sent when the form is submitted. I would like to have the id as well.

some silly test code:

<legend>Who Sings in the Shower?</legend>
<label for="bob">Bob</label>
<input type="radio" name="sings" id="bob" value="yes"/>
<label for="jane">Jane</label>
<input type="radio" name="sings" id="jane" value="no" />
<label for="kelly">Kelly</label>
<input type="radio" name="sings" id="kelly" value="no" />
</fieldset>```



If someone clicks "Bob", then submits the form, I would like both "yes" and "bob" to be sent to the script, where I can capture the values with variables. If I don't need jQuery to do this, so much the better. ;-)

How do you have form and the submit button set up? Could you include that, all well as the PHP script you’re calling with it?

<input type="submit" name="submit" id="submit" />

It’s pretty standard. I’m just using $_POST to get the value for “sings” (either yes or no) , assigning it to a variable, and not doing anything fancy with it yet. Baby steps!

My (perhaps simplistic) thinking was that if I could get the value of the id of the selected radio button sent via a hidden form field (not yet on the form above!) that might work, but hadn’t found a way to do that task:

<input type="hidden" name="individual" id="the value for whatever the id was on the radio button that was selected" />``


Then it would be easy to retrieve it in the script:

$individual = $_POST['individual'];

Hi,
Perhaps something like this

<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#my_form').on('change', function(event) {
    	$('<input />').attr('type', 'hidden')
        .attr('name', 'id')
        .attr('value', event.target.id)
        .appendTo(this);
        
        $(this).submit();
    });
});
</script>
</head>
<body>
    <form method="POST" id="my_form">
        <fieldset>
            <legend>Who Sings in the Shower?</legend>
            <label for="bob">Bob</label>
            <input type="radio" name="sings" id="bob" value="yes"/>
            <label for="jane">Jane</label>
            <input type="radio" name="sings" id="jane" value="no" />
            <label for="kelly">Kelly</label>
            <input type="radio" name="sings" id="kelly" value="no" />
        </fieldset>
    </form>
</body>
</html>

Then handle the POST values in php.

1 Like

I will give this a try!

Flippin’ beautiful. Simple and perfect for my needs. Thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.