The Codesee The Codesee - 6 months ago 10
HTML Question

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.

When using the code below, the border colour doesn't change and the following error displays:


Uncaught TypeError: Cannot read property 'style' of 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>

Answer

You need to add window.onload = function () { to the top of your script.

<?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>