Search code examples
phpjquerypostget

Dynamic list of radio buttons - how do I retrieve value instead of retrieve BY VALUE


I have a list of radio buttons that gets loaded from a database. $missing below is a mysql query result in which I retrieve labels for my radio buttons. That part works a-okay:

<div id="container">
<div id="col1">
    <div>
        <div id="dam_return">
        <form method="post" action="#" >';
        foreach ($missing as &$path) {
            $prov = $path['template_name'];
            $return .= '<input type="radio" name="radio_group1" value="$prov" class="radios">'.$prov."</option>";
            $return .= '<br>';
        }   
    $return .= '</form>';

I inject this return value from the above into my HTML elsewhere in my PHP code (and yes I properly close the divs after, etc.). This part works fine so far.

So then, I have a listener for my class of radio buttons:

$(".radios").click(function () {
        $('[id$=mytextbox]').val("asdadasd");
        $.get('?page=EntitlementTemplates&action=dothething&var1=somestuff', function() {
                $(node).removeClass('selected');
                $(node).addClass('delete');
            });

    //location.reload();
});

Now here is me reading my get:

 if (isset($_GET['action'])) {
            switch (strtolower($_GET['action'])) {

                case 'dothething' :
                //I want to manipulate/identify the selected radio button
                break;

In this get code, I want to get the value of the radio button that is pressed. There are many examples online using a switch statement for a discrete list of values... but I want to retrieve the radio button BY value. I will use this radio button value to then load some new data to the page... but right now I don't know how to get what radio button was selected? I can't seem to find anything for this scenario.


Solution

  • In order to pass the clicked element value to your server in your click event hanler, you have to pass it as a parameter in your GET-request query.

    In your click handler:

    $(".radios").click(
            $('[id$=mytextbox]').val("asdadasd");
            var radioValue = $(this).val(); 
            $.get('?page=EntitlementTemplates&action=dothething&var1=somestuff&clickedRadioValue='+radioValue , function() {
                    $(node).removeClass('selected');
                    $(node).addClass('delete');
                });
    
        //location.reload();
    });
    

    In your php script:

    if (isset($_GET['action'])) {
                switch (strtolower($_GET['action'])) {
                    case 'dothething' :
                    $clickedRadioValue = $_GET['clickedRadioValue'];
                    //further manipulations
                    break;
    
                   //other cases
                }
    }