Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a radio button return boolean true/false instead of on/off

I want that my radio buttons return me a Boolean value true or false instade of on/off

So I pass the true/false in the value of the input :

<label>Male
   <input type="radio" name="IsMale" value="true" />
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" />
</label>

but it returns me a true/false in a text format. Please masters how could I get them in a booleen format ?

More details : In fact I need to store my $_POST array in a file.txt, and for my radio button I need to store for example :

array ( "IsMale" => true );

and not :

array ( "IsMale" => "true" );
like image 354
Sami El Hilali Avatar asked Dec 20 '12 09:12

Sami El Hilali


People also ask

Do radio buttons return Boolean?

Return value: It returns a Boolean value which represents that the radio button is checked or not.

Is a radio button Boolean?

<input type="radio">

How do I keep a radio button checked by default?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

Can I unselect radio button?

The reason why it's impossible to deselect HTML “radio” inputs. Radio buttons are not supposed to be left blank. They can be left blank only if you do not want to use default values. This allows you to do things like force the user to fill in the form and not assume anything by default if it is required.


1 Answers

You cannot make radio buttons or any other form element directly submit a PHP true value, only a string such as "true".

To solve your problem, you would have to change the value of the $_POST item in your PHP file.

//Form has been submitted
if(isset($_POST['submit'])) {

    //Radio button has been set to "true"
    if(isset($_POST['IsMale']) && $_POST['IsMale'] == 'true') $_POST['IsMale'] = TRUE;

    //Radio button has been set to "false" or a value was not selected
    else $_POST['IsMale'] = FALSE;

}

Edit: Ben has provided a functional solution using ternary operators which is a shorter alternative. The example above may clarify exactly what is going on in the process (in a more verbose form).

like image 93
Dan Greaves Avatar answered Sep 17 '22 03:09

Dan Greaves