简体   繁体   中英

How to change the background color of a html page using forms and php?

After inputting a color of choice the page should change its background color. It should be done using html forms.

<body bgcolor="<?php $_GET["color"]; ?>">
    <form method="get" name="color">
        Background color:<br>
        <input type="text" name="color">
        <input type="submit" value="submit">
    </form>
</body>

You have to echo the value stored in the variable $_GET["color"] like

<body bgcolor="<?php echo $_GET["color"]; ?>">

and you should also check if the variable $_GET["color"] exist and not null using isset() like

<body bgcolor="<?php echo ( isset($_GET["color"]) && $_GET["color"] ) ? $_GET["color"] : "pink"; ?>">   // here pink is the default color
    <?php if(!empty($_GET['color']) {?>
        <body style="background-color:'<?php echo $_GET['color'];?>">
    <?php }else {?>
        <body style="background-color:orange">
    <?php } ?>
    <form method="get" name="formcolor">
            Background color:<br>
            <input type="text" name="color">
            <input type="submit" value="submit">
        </form>
    </body>

You should use CSS instead of HTML attributes to decorate your HTML rendering. Also you should avoid to use inline styling which represents a better organization since it's separating languages (= separating your CSS from your HTML).

So to answer your question, you can do that :

<?php
    if (!isset($_GET["color"]) || $_GET["color"] === '')
    {
        $_GET["color"] = 'pink';
    }
?>
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>My Website</title>
        <style>
            body {
                background-color: '<?= $_GET["color"] ?>';
            }
        </style>
    </head>
    <body>
        <form method="get" name="color">
            Background color:<br>
            <input type="text" name="color">
            <input type="submit" value="submit">
        </form>
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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