简体   繁体   English

如何使单选按钮返回布尔值true / false而不是on / off

[英]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 我希望我的单选按钮返回一个布尔值true或false的开/关开启

So I pass the true/false in the value of the input : 所以我在输入值中传递true / false:

<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. 但它以文本格式返回true / false。 Please masters how could I get them in a booleen format ? 请掌握我如何以booleen格式获取它们?

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 : 更多细节:事实上我需要将我的$ _POST数组存储在file.txt中,对于我的单选按钮,我需要存储例如:

array ( "IsMale" => true );

and not : 并不是 :

array ( "IsMale" => "true" );

You'll have to check the data and modify it. 您必须检查数据并进行修改。

if(isset($_POST['SubmitButton'])) { 

  $_POST['IsMale'] = $_POST['IsMale'] == 'true' ? true : false;
}

You cannot make radio buttons or any other form element directly submit a PHP true value, only a string such as "true". 你不能使单选按钮或任何其他表单元素直接提交PHP真值,只能是一个字符串,如“true”。

To solve your problem, you would have to change the value of the $_POST item in your PHP file. 要解决您的问题,您必须更改PHP文件中$ _POST项的值。

//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. 编辑: Ben提供了一个使用三元运算符的功能解决方案,这是一个更短的选择。 The example above may clarify exactly what is going on in the process (in a more verbose form). 上面的例子可以准确地澄清过程中发生了什么(以更详细的形式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM