I am running an ajax call and when i try to submit, my input field gets an another div underneath it and shows error, but if i click the button too many times, it keeps on adding new messages one under the another
and also i want to hide the message after 3 seconds
so basically two problems in my code
$.ajax({
url : $('##frm').attr('data-action'),
type: 'post',
data: $('##frm').serialize(),
success: function(data) {
if (data.indexOf("emailissue") > -1) {
$("##emailaddress").parent().after("<div class='validation' style='color:red;font-size:0.90em;'>Please Provide valid email address</div>");
$('##validation').delay(3000).fadeOut();
}else{
$("##ID").show().delay(5000).fadeOut();
$("##ID").css('display','none');
}
}
});
html is like this
<div class="form-group">
<label for="emailaddress">We are missing you email, please enter below</label>
<input type="text" name="emailaddress" id="emailaddress" placeholder="Enter your email" class="form-control">
</div>
CodePudding user response:
Why do you have double '##' when you try to select the element?
Also after 3 second you need to remove the new created div from the DOM,
it's not enough to just call the fadeOut()
(my guess it's just set opacity 0)
CodePudding user response:
Try setting a static response element in the DOM:
<div class="form-group">
<label for="emailaddress">We are missing your email, please enter it below</label>
<input type="text" name="emailaddress" id="emailaddress" placeholder="Enter your email" class="form-control">
<div id="response" class="validation"></div>
</div>
Then in the response from your ajax call, update the contents and visibility of the #response
element:
if (data.indexOf("emailissue") > -1)
{
$("#response").show().text('Please Provide a valid email address');
setTimeout(function(){
$('#response').fadeOut();
}, 3000);
}
By toggling between hiding/showing the #response
element, we no longer need to worry about additional response elements being added, or deleting older ones.
Here is a DEMO I made. Click the "Test" button to the right to see it.