user3158009
user3158009

Reputation: 35

call a JS function inside an event method

I hope I'm not repeating a question but I've searched around and couldnt find help so I thought I should ask directly, I'm still a beginner and this is an assignment for my class so please be as thorough as possible

I'm trying to create a form where as the user clicks on another field, it checks if the input he put in the first one is as required by the website, without having to click enter or a submit button.

this is the HTML file.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="test.js"></script>  
<script>

$(document).ready(function(){
    $("div.ID").focusin(function(){
        $(this).css("background-color", "#FFFFCC");
    });
    $("div.ID").focusout(function(){
        $(this).css("background-color", "#FFFFFF");
        userid_validation(userid,5,12);

    });
});
</script>
</head>
<body>

<div class="ID" >
  User ID: <input type="text" name="userid" size="12" />
 </div>

 <div class="pass">
 Password: <input type="text" name="psw" size="12" />
 </div>

</body>
</html>

and this is the JS file

function userid_validation(userid,mx,my)  
{  
var uid_len = userid.value.length;  

if (uid_len == 0 || uid_len >= my || uid_len < mx)  
{  

alert("User Id should not be empty / length be between "+mx+" to "+my);  

//uid.focus();  
return false;  
}  

return true;  
}  

I'm most probably doing something completely wrong but I don't know what. thanks in advance !

Upvotes: 0

Views: 56

Answers (1)

ScanQR
ScanQR

Reputation: 3820

You need to apply focusin and foucsout on input elements. Currently you have applied it on div. Also you have code error on calling following function,

userid_validation(userid, 5, 12); // userid not defined.

Please check if this works.

function userid_validation(userid, min, max) {
  var uid_len = userid.length;

  if (uid_len == 0 || uid_len > max || uid_len < min) {

    alert("User Id should not be empty / length be between " + min+ " to " + max);

    //uid.focus();  
    return false;
  }

  return true;
}
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="test.js"></script>
  <script>
    $(document).ready(function() {
      $("div.ID").find('input').focusin(function() {
        $(this).css("background-color", "#FFFFCC");
      });
      $("div.ID").find('input').focusout(function() {
        $(this).css("background-color", "#FFFFFF");
        userid_validation($(this).val(), 5, 12);

      });
    });
  </script>
</head>

<body>

  <div class="ID">
    User ID:
    <input type="text" name="userid" size="12" />
  </div>

  <div class="pass">
    Password:
    <input type="text" name="psw" size="12" />
  </div>

</body>

</html>

Upvotes: 1

Related Questions