在表单中发生错误时使文本框颜色变为红色

时间:2012-05-16 20:25:05

标签: php html css forms

我需要你的帮助..我正试图在表格中出现错误时将文本框设为红色...

这就是我能做到的。但是,当我提交时,我会在表格

中获得未定义索引 error_css
 if (isset($_POST['submit'])) { 
 if (empty($_POST['username'])) {
       $error_css='background-color:red';
 }

表格

<label for="username">Username:</label>
<input id="username" type="text" value="<?php if(isset($_POST['username'])){ echo $_POST['username']; } ?>" name="username" title='Username' />
谢谢你的时间......

5 个答案:

答案 0 :(得分:1)

您从未在html标记中设置样式,并且{if {}}语句中的第一个是冗余的。它应该是:

<label for="username">Username:</label>
    <input type="text" <?php 
        if(isset($_POST['username'])) { 
            echo 'value="'.$_POST['username'].'"'; 
        } else {
            echo 'style="background-color:red"';
        }
    ?> name="username" title='Username' >

答案 1 :(得分:0)

您的变量$error_css为空/不存在。

我认为脚本开头的2个案例永远不会达到$error_css获取其内容的程度。

答案 2 :(得分:0)

如果可以的话,为什么不寻找像jQuery validation plugin这样的解决方案呢?它不是一个完整的解决方案,因为你仍然需要某种服务器端验证,但它会帮助你。

答案 3 :(得分:0)

表格

<label for="username">Username:</label>
<input id="username" type="text" value="<?php echo @$_POST['username']; ?>"
   name="username" title='Username' style="<?php echo @$error_css; ?>"/>

答案 4 :(得分:0)

尝试这样的事情:

<?php

$username = "";
$error_css = "";

if (isset($_POST['submit'])) {
    if(isset($_POST['username']))
        $username = $_POST['username'];
    else
        $error_css='background-color:red';
}

?>

<label for="username">Username:</label>
<input id="username" type="text" value="<?php echo $username; ?>" name="username" title='Username' style="<?php echo $error_css; ?>"/>