Search code examples
phpjavascripthtmlradio-buttonmessagebox

PHP - Display message directly after selecting a Radio Button


I am using a PHP script, but say I had two radio buttons, right?

How could I actually execute code, such as (main intention | display a messagebox) upon selection of one or the other?

Say I had a radio button named RadioButton1, Once checked/selected, a message box would appear saying RadioButton1 Selected?

Is this possible through PHP alone? Or do I need to integrate an html page which posts to the PHP page?


Solution

  • Use Javascript for client side interaction like that. The code below listens for the onchange event and shows an alert().

    jsFiddle Demo

    <input type="radio" name="myradio" value="RadioButton1" />
    <input type="radio" name="myradio" value="RadioButton2" />
    <input type="radio" name="myradio" value="RadioButton3" />
    
    <script>
    ​window.onload = function()
    {
        var radios = document.getElementsByName("myradio");
         for(var i=0; i<radios.length; i++)
         {
            radios[i].onchange = function()
            {
                if(this.checked)
                {
                    alert(this.value + " selected");
                }
            }
         }             
    }​
    </script>
    

    The first 3 lines are the radio buttons HTML. After that we have the <script> tag which denotes Javascript code. The Javascript is adding some code to the onload event, which simply means: execute this code when the page is loaded. Next we get all of the radio button elements into an array called radios - for that we use getElementsByName() passing the radio button group name which is myradio. Next we loop through each radio button in the array and assign an onchange handler, which means: execute this code when each radio button is changed. Within that, we check if the radio button is checked and if it is, we show the alert, showing the radio button's value which will be RadioButton1, RadioButton2, RadioButton3.