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条回答
Root(大扎)
2楼-- · 2019-01-20 10:02

you can change the get_option() function to be something like

function get_option($name) {
   $defaults = array(
      'fist_name' => 'Mike',
      'fist_name' => 'Wordpressor',
      'my_name' => 'Dunno'
   );
   // get the value from the $defaults array
   $val = $defaults[$name];

   // but if the same value has already been posted - replace the default one
   if (isset($_POST[$name])) {
      $val = $_POST[$name];
   }
   return $val;
}
查看更多
聊天终结者
3楼-- · 2019-01-20 10:02

Simply use a ternary operator. its pretty easy try this

$default = 'Mike';

$your_name = get_option('your_name');

$condition = !empty($your_name) ? $your_name : $default;

<input type="text" name="your_name" value="<?php echo $condition; ?>" />
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-20 10:07

You need to check the return of get_option first, and substitute something if a default is not available

<?php
    $default = get_option('your_name');
    if( $default == "")
    {
        $default = <whatever your default value is>;
    }
?>
<input type="text" name="your_name" value="<?php echo $default; ?>" />

Change get_option to return an empty string (or something else) if the default is not available.

查看更多
放我归山
5楼-- · 2019-01-20 10:07

You can do a switch statement and have default to be whatever you want it to be.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-20 10:10

Set some variable at start with the post variables.

like

$name_val = "";
if(isset($_POST["your_name"])
{
    $name_val = $_POST["your_name"];
}

<input type="text" name="your_name" value="<?= $name_val?>">
查看更多
欢心
7楼-- · 2019-01-20 10:17

This is How I solved this issue in my problem which I believe is similar, when $_POST is read the value is populated from the $_POST value else sets a default of Mike

value="<?php if (isset($_POST['name'])) echo $_POST['name']; else echo "Mike"?>" >

Hope this helps someone oneday

查看更多
登录 后发表回答