2

I am trying to get an alert whenever a user clicks on the username or password input field and exits it without entering. However, I am able to get this to work after using "onblur" instead of "onfocus" (Thanks to Gurvinder's answer below). Now, the alert seems to work for both the fields when I click outside of the form using "onfocus". However, when I use tab key to get to password field from username field to password field, the "passwordCheck" function keeps running. Please help.

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript exercises</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form name="myForm" >
            <table>
                <tr>
                    <td>Username:</td>
                    <td><input name="username" id="userName" type="text" onfocus="userNameCheck();"></input></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input name="password" id ="password" type="password" onfocus="passwordCheck();"></input></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="Button" value="Submit"></input></td>
                </tr>
            </table>    
        </form>     
        <script>

            //User name field validator - Alert a message for empty input fields
            var userNameCheck = function() {
                if(document.myForm.username.value == ""){
                    alert("User Name cannot be blank"); 

                }
                else{
                    return false;
                }
            }

            //password field validator - Alert a message for empty input fields
            var passwordCheck = function() {
                if(document.myForm.password.value == ""){
                    alert("Password cannot be blank");

                }
                else{
                    return false;   
                }
            }
        </script>
    </body>
</html>
rahulsim2012
  • 25
  • 1
  • 5
  • Don't show an alert because that's really annoying. Just use the HTML5 pattern attribute to test to see if the input is empty. If it is the input will show up red to alert the user. Something like `[a-z-A-Z0-9]{1}` which checks that at least one character is present. – Andy Nov 10 '17 at 15:05
  • 1
    Possible duplicate of [Run JavaScript when an element loses focus](https://stackoverflow.com/questions/769135/run-javascript-when-an-element-loses-focus) – Polina F. Nov 10 '17 at 15:05
  • Why not just select the element of interest explicitly? document.getElementById("username") instead of document.myForm.username.length ah, maybe your onfocus is not even called... right? – Harry Nov 10 '17 at 15:06
  • Note, `` element is self-closing – guest271314 Nov 10 '17 at 15:33
  • possible duplicate https://stackoverflow.com/questions/28091261/javascript-live-validation – Vivek Kumar Nov 10 '17 at 19:51

2 Answers2

1

I want the username input to show an alert if the user clicks on it and tabs to the next field without entering any data.

If you are using focus event to check for the input validity, then unless value is pre-populated, alert will keep coming.

Use blur event, onblur instead of onfocus.

<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input></td>

Demo

<body>
  <form name="myForm">
    <table>
      <tr>
        <td>Username:</td>
        <td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input>
        </td>
      </tr>
      <tr>
        <td>Password:</td>
        <td><input name="password" id="password" type="password"></input>
        </td>
      </tr>
      <tr>
        <td></td>
        <td><input type="Button" value="Submit"></input>
        </td>
      </tr>
    </table>
  </form>
  <script>
    //User name field validator - Alert a message for empty input fields
    var userNameCheck = function() {
      if (document.myForm.username.length >= 1) {
        //Nothing happens
      } else {
        alert("User Name cannot be blank");
        return false;
      }
    }
  </script>
</body>
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Thank you Gurvinder..onblur seems to fix the issue. However, I am getting repeated alerts from passwordCheck function now – rahulsim2012 Nov 10 '17 at 16:13
  • You need to follow the same approach for the password as well. – gurvinder372 Nov 10 '17 at 16:53
  • Yes Gurvinder, I am using onblur for both password and username fields. For username the alert seems to work, but for password, the Alert is in infinite loop – rahulsim2012 Nov 10 '17 at 17:00
  • //User name field validator - Alert a message for empty input fields var userNameCheck = function() { if(document.myForm.username.value != ""){ //Nothing happens } else{ alert("User Name cannot be blank"); } } //password field validator - Alert a message for empty input fields var passwordCheck = function() { if(document.myForm.password.value != ""){ //Nothing happens } else{ alert("Password cannot be blank"); return false; } } – rahulsim2012 Nov 10 '17 at 17:02
  • I have updated the new code in my question, You just need to change onfocus to onblur – rahulsim2012 Nov 10 '17 at 17:05
  • @rahulsim2012 if your requirement is to not let the user move out of a field unless it is valid, then this behavior is expected since on-tab-event blur event will be invoked as well. If you don't want to hold the user on the same field at blur event, then simply remove `return false`. – gurvinder372 Nov 13 '17 at 07:02
0

Why not create your own 'alert' div for more control (and better user experience).

$("input").focus(function(){
      var x = document.forms["myForm"]["password"].value;
        if (x == "") {
            /*alert("Password cannot be blank");*/
            $('.alert').show();
            return false;
       }
});

And to specify tab key scenario, try:

function checkTabPress(key_val) {
    if (event.keyCode == 9) {
        $('.alert').hide();
    }
}
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • Yes. This is exactly what I am looking for. But the problem is, If I use the Tab key to proceed to the next field, the alert keeps repeating. – rahulsim2012 Nov 10 '17 at 16:22
  • Gotchya - updated. Hope it helps. I'd create my alert elem based on your needs. – Dr Upvote Nov 10 '17 at 16:30