Balaji Ravichandran Balaji Ravichandran - 6 months ago 40
Javascript Question

jQuery delay() function not working

I need to show a success message upon the change of password, the issue is success message displays and vanishes in no time even though I increase the delay time.
For testing you have to give same password and confirm password value

Here is the code,

<div class="modal-body">
<div class="row">
<div class="col-md-2"></div>.

<!-- This is the div where I display message -->

<div class="col-md-8" id="alert-msg" style="display: none;">
<div style="text-align: center;" class="alert alert-success">
<strong>Success! Your Request Has Been Submitted!!</strong>
</div>

</div>
</div>

<form class="form col-md-12 center-block" id="pass" method="GET" action="index.php">
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Password" name="pass1" id="f_pass">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Confirm Password" name="pass2" id="c_pass">
</div>
<div class="form-group">
<button type="submit" id="msg-sub" class="btn btn-primary btn-lg btn-block">Submit</button>
</div>
</form>
</div>


This is the script part,

<script>
$("#msg-sub").click(function(){
var pass1= $("#f_pass").val();
if(pass1 !=='') {
$('#alert-msg').show(0).delay(3000).hide(0);
}
});
</script>


Here is the url,

Please help me out, Thanks in advance!!!

Answer

The error is with the script, you need to wrap it inside jQuery .ready method. You also need to prevent the click handler propagation by using event.preventDefault()

<script>
 $(document).ready(function(){
   $("#msg-sub").click(function(){
     var pass1= $("#f_pass").val();              
     if(pass1 !=='') {
       $('#alert-msg').css('display', 'block').delay(3000).fadeOut(600);    
     }
     e.preventDefault();
   }); 
 });        
</script>

Here's a link to the codepen: http://codepen.io/anon/pen/vKLdJj