简体   繁体   English

如果输入为空,边框颜色不会改变

[英]Border colour isn't changing if input is empty

I have a simple script written in PHP and Javascript which changes the border colour of an input field if it is empty. 我有一个用PHP和Javascript编写的简单脚本,如果input字段为空,它将更改input字段的边框颜色。

When using the code below, the border colour doesn't change and the following error displays: 使用以下代码时,边框颜色不会更改,并且会显示以下错误:

Uncaught TypeError: Cannot read property 'style' of null 未捕获的TypeError:无法读取null的属性“样式”

<?php
if(isset($_POST['submit'])) {
if(empty($_POST['username'])) {
echo'
<script>
document.getElementById("username").style.border = "1px solid red";
</script>
';
}
}
?>

<form method="post">
<input type="text" id="username" name="username">
<input type="submit" name="submit">
</form>

You need add window.onload = function () {...} to the top of your script. 您需要在脚本顶部添加window.onload = function () {...}

<?php

if (isset($_POST["submit"])) {

    if (empty($_POST["username"])) {

        echo "
            <script>
                window.onload = function () {

                    document.getElementById('username').style.border = '1px solid red';
                };
            </script>";
    }
}

<form method="post">
    <input type="text" id="username" name="username">
    <input type="submit" name="submit">
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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