简体   繁体   中英

jQuery setTimeout won't work

I'm trying to compare two password fields and show a Popover if they don't match.

HTML

<div class="form-group col-lg-6">
    <label>Password</label>
    <input type="password" class="form-control" name="password" id="password" required data-toggle="popover" title="Password Strength" value="" placeholder="Enter your password...">
</div>
<div class="form-group col-lg-6">
    <label>Repeat Password</label>
    <input type="password" class="form-control" name="passwordrep" id="passwordrep" value="" data-bind="popover" data-content="No match" placeholder="Confirm password...">
</div>

My jQuery Code works if i'm not using setTimeout. But i want to wait for a few seconds before showing the "no match" popover.

JS

function showPopover(id){
  $(id).popover('show');
}

var x_timer;

$("body").delegate('#passwordrep', 'keyup', function(){
    clearTimeout(x_timer);

    if($(this).val() != $('#password').val()){
      x_timer = setTimeout(function(){showPopover(this);}, 1000);
    }
    else {
      $(this).popover('hide');
    }
});

this doesn't refers to element which invoked the event handler in the setTimeout argument. You can pass parameters to setTimeout which will be available to the function

setTimeout(function(elem){
   showPopover(elem);
}, 1000, this);

Note: delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7,


You can also use .bind()

setTimeout((function(){
   showPopover(this);
}).bind(this), 1000);
function checkPassword(elt1,elt2){
    return elt1.value()==elt2.value();
}

you can call it on keyup , you can add if to show some message

Thanks! It worked with .bind() I love you guys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM