Skip to content
Advertisement

alert down on inputbox

how can i bring All fields are required! Error Alert down to input box like

show error that username filed required down on username input filed

same to password filed down on inputbox

<!DOCTYPE html>
<html>
<body>

<script>

function switchVisible() {
               var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;

        if(username == "" || password == ""){
            alert("All fields are required!");
            return false;
        }
                        
}

</script>


  <input type="text" id="username" name="username" placeholder="username">
  <! -- show error here for no input in filled username -->
  <input type="password" id="password" name="password" placeholder="password">
  <! -- show error here for no input in filled password -->
  <input type="button" value="Submit" onclick="switchVisible();">

</body>
</html>

Advertisement

Answer

An alert always appears at the top of the page. If you want some kind of indication below your input fields, you could add a <p> below each of them, and set the text with js like so:

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="username" name="username" placeholder="username">
  <p id="usernameError"></p>
  <input type="password" id="password" name="password" placeholder="password">
  <p id="passwordError"></p>
  <input type="button" value="Submit" onclick="switchVisible();">

  <script>
     function switchVisible() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;

        if(username == "" || password == ""){
            document.getElementById("usernameError").innerHTML = "please give a username";
            document.getElementById("passwordError").innerHTML = "please give a password";
            return false;
        }              
     }
  </script>
</body>
</html>

You should probably make a seperate if for username and password, or make one <p> for both error messages. Also, <script>‘s should be at the bottom of the <body>, or in a different file.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement