当表单出现错误时,使文本框变为红色。

3

我需要你的帮助。我正在尝试在表单中出现错误时使文本框变红...

这是我能做到的。但是当我提交表格时,我会得到一个未定义的索引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' />

thanks for your time...


</label>之间的巨大空格是怎么回事?另外,请发布所有您的代码。 - Daedalus
用户,我添加了id="username"只是因为我看到你使用相同的标签,并且你一直缺少它。FOR是对表单元素ID的引用。 - Roko C. Buljan
@user1378680 请发布您的其余代码;最好是那部分实际调用了您的$error_css变量的部分。 - Daedalus
5个回答

0

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

我认为你脚本开头的两个if语句从未到达$error_css获取其内容的点。


0
如果可以的话,为什么不考虑使用jQuery验证插件这样的解决方案呢?它并不是一个完整的解决方案,因为你仍然需要一些服务器端验证,但它会让你上路。

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; ?>"/>

;) 是为了缩短代码而存在的。这种方法是没有希望的,所以我认为也可以滑入其中。 - Majid Fouladpour
2
如果您添加了标签“for”引用的“ID”,我会点赞此操作。 - Roko C. Buljan
@RokoC.Buljan - 哈哈,开玩笑的,感谢你指出这个遗漏。 - Majid Fouladpour
2
for是用于引用name而不是id - Jeff Hines
@user1378680 - 你从PHP得到了什么? - Majid Fouladpour
显示剩余3条评论

0

你从未在HTML标签中设置样式,而且第一个if{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' >

并不实际工作,它只是在屏幕上打印出style="background-color:red"。 - Yunfei Chen
@Yunfei Chen,你错了,这个是可以工作的。复制并粘贴这个完整的脚本,你会看到它确实可以工作。 - Orbiting Eden

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; ?>"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接