SetTimeout Does not work for validation in jQuery -
below code: have written function form validation , works well. want call validation function after few seconds because feels more comfortable warn users few seconds after type field , it's less shocking. problem when paste "//this code" "//here" doesn't work , "settimeout called" doesn't show in console, , console triggers "if()" line in settimeout scope. guess problem scope of $(this) inner function don't know how solve it! :)
var firstname = $('#firstname'); var reg_firstname = /^[a-za-z]{1,50}$/; var color_valid = "#e0ffe0"; var color_invalid = "#e09898"; var unable_btn = false; function validform (variable, reg_variable) { variable.on('keyup',function(){ settimeout(function(){ // here: console.log("settimeout called"); // called },5000); //this code: if (reg_variable.test($(this).val()) == false || $(this).val().trim().length == 0) { $(this).css("background-color", color_invalid); unable_btn = false; console.log("reg: " + reg_variable.test($(this).val())); console.log("length: "+ $(this).val().trim().length); console.log("btn: " + unable_btn); console.log("==========="); } else { $(this).css("background-color", color_valid); unable_btn = true; console.log("reg: " + reg_variable.test($(this).val())); console.log("length: "+ $(this).val().trim().length); console.log("btn: " + unable_btn); console.log("==========="); } }); } validform(firstname,reg_firstname);