Search code examples
htmlformsradio-buttonform-parameterselect-options

Replace select dropdown with radio button with functionality


I have a dropdown with male and female options. I am replacing it with radio buttons, I wrote the HTML, but for the HTML form to work where should I place name attribute on radio button

HTML for dropdown

<select id="gender" name="gender" title="Gender">
   <option value="1" selected="selected">Male</option>
   <option value="2">Female</option>
</select>

HTML for radio

<input type="radio" title="Gender" value="1"> Male
<input type="radio" title="Gender" value="2" checked="checked"> Female

For select, the name attribute will work when we submit the form, as it will send the select option as name parameter. But where should I put name attribute for radio buttons? If I put name attribute for both attribute same, it won't work as two radio button cannot have the same name.

As I don't want to change the backend code, I want to work as before as it is for the select option, which used to send selected option through name attribute,

How to do the same for radio buttons. So that when any radio buttons are selected it sends the selected element in name parameters which doesn't require a change in backend code


Solution

  • So you can post unique values like this (to the same $_POST variable), HTML:

    <input type="radio" title="gender" name="gender" value="1">Male
    <input type="radio" title="gender" name="gender" value="2">Female
    

    Access them in PHP with:

    $gender = $_POST['gender'];
    

    If you have a situation where you can select more than one radio button you can use an array, HTML:

    <formgroup>
        <input type="radio" title="gender" name="something[0]" value="1">
        <input type="radio" title="gender" name="something[0]" value="2">
    </formgroup>
    <formgroup>
        <input type="radio" title="gender" name="something[1]" value="1">
        <input type="radio" title="gender" name="something[1]" value="2">
    </formgroup>
    

    Then in PHP you can access these values using:

    $radio1 = $_POST['something'][0];
    $radio2 = $_POST['something'][1];