Reputation: 239
I am using the jQuery load() method to load content into a page depending on the value added into an input field. For some reason I am getting multiple ajax calls at once so the content I am calling is appearing twice in the page rather than just once.
Hope that makes sence!
Here is the code I am working on:
function Acun () {
var firstChar = $('#accountnumber').val().charAt(0);
if(firstChar != 'x' && firstChar != 'X'){
$('#examplepagecontent').html('<div id="invoice-loader"></div>');
$("#examplepagecontent" ).load( "/product/pay-an-invoice #content");
}
else {
$('#examplepagecontent').html('<div id="invoice-loader"></div>');
$("#examplepagecontent").load("/product/pay-an-invoice-with-account-z #content");
}
}
HTML:
<input type="text" name="Account Number" value=""
id="accountnumber" name="accountnumber" onKeyUp="Acun();" maxlength="7"/>
Upvotes: 1
Views: 70
Reputation: 28366
You are calling the Acun()
function on onKeyUp="Acun();"
event. This event happen each time the user presses the button.
You should check the other requests are pending, and do not request the new one, or you can check the length of textbox
input, and make a request with largest one.
Upvotes: 1
Reputation: 51
You are calling the function every keyUp. This means every time a character is entered with, when the button is lifted, the function will run.
You would want to try something like this
var timer; //important to have variable outside the function
function Acun () {
window.clearTimeout(timer);
timer = window.setTimeout(function(){
var firstChar = $('#accountnumber').val().charAt(0);
if(firstChar != 'x' && firstChar != 'X'){
$('#examplepagecontent').html('<div id="invoice-loader"></div>');
$("#examplepagecontent" ).load( "/product/pay-an-invoice #content");
}
else {
$('#examplepagecontent').html('<div id="invoice-loader"></div>');
$("#examplepagecontent").load("/product/pay-an-invoice-with-account-z #content");
}
},500); //run after a half second of no activity
}
Upvotes: 1