HTML/PHP - default input value

2019-01-20 09:43发布

I have a post php form and a set of inputs:

  1. Your Name
  2. Your Last Name
  3. My Name

Every input looks the same, only the names change:

<input type="text" name="your_name" value="<?php echo get_option('your_name'); ?>" />

How to set default values when value= is not available?

[edit]

Ok, so, normally I'd do something like:

<input type="text" name="your_name" value="Mike" />

But in this case I have a PHP script that grabs inputs data and displays it using value="<?php echo get_option('your_name'); ?>" . So I have no idea how to force my form to display "Mike" in my input.

10条回答
We Are One
2楼-- · 2019-01-20 10:18

You could use my tiny library ValueResolver in this case, for example:

$default = ValueResolver::resolve(get_option('your_name'), '<whatever your default value is>');

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

查看更多
祖国的老花朵
3楼-- · 2019-01-20 10:23

I agree with Teneff but I would break it out.

In the index.php I would have the following at the top of the doc

<?
$defaultText = include 'default_text.php';  
?>

where your forms are it would be:

<form method="post" action="">
<input id="names"><? echo $defaultText; ?> </input> 
</form> 

then I would have a seperate file on the root level called "default_text.php."

<?
$Name = <<<EOD Name EOD;
return $Name;
?>
查看更多
Emotional °昔
4楼-- · 2019-01-20 10:23
<input type="text" name="your_name" value="<?php echo empty(get_option('your_name')) ? "TheDefaultValue" : get_option('your_name'); ?>" />
查看更多
萌系小妹纸
5楼-- · 2019-01-20 10:24

Since value is the default, just add a condition around your get_option-function, maybe something like this:

<input type="text" name="your_name" value="<?php $var = get_option('your_name'); if ($var == '') $var = 'your_default'; echo $var; ?>" />
查看更多
登录 后发表回答