hendrix hendrix - 5 months ago 13
jQuery Question

How to use Jquery blur function properly

I want to know if this is a proper usage of the

.blur
function, since I have a larger code with many validations and a
.blur
for each one and does not work, maybe I'm doing it wrong. I will comment how I understand it.

$(document).ready(myFunction); //.ready function runs myFunction

//"userinfo" is a text field that when loses focus it runs validateuser function

function myFunction(){
$("userinfo").blur(validateuser);
}

function validateuser(){
var user = $("#userinfo").val(); //variable stores data input from the user

//validates that the user contains text only, showing messages accordingly

if(/^[a-zA-Z]+$/.test(user)){
$("#msg").html("The information is correct.");
}else{
$("#msg").html("The information is not correct");
}
}

Answer

JavaScript :

function validateuser(){
   var user = $("#userinfo").val();
   if(/^[a-zA-Z]+$/.test(user)){ 
      $("#msg").html("The information is correct.");
   }else{
      $("#msg").html("The information is not correct");
   }
}

$(document).ready(function(){
   $("#userinfo").blur(function(){
      validateuser();
   });
});

Use this code.You can create function within $.ready() or outside.It doesn't matter.Call that validateuser() function when $("#userinfo").blur() event.

Comments