I have an ajax call that gets fired after the onkeyup event of an input. Once 8 numbers have been entered, it makes a call.
If the call was successful, it adds a new row to a table.
The problem is that it’s adding 2 rows. The ajax call if being fired twice as well. If I have the debugger is running, it only adds 1 row. If have an alert for when the row is added, it only adds 1 row. If I don’t have the debugger or the alert, it adds 2 . Not sure why.
The input:
<input style="width:100px" type="text" id="account0" maxlength="8" onkeyup="getAccount(this);" />
The function, addrow is being fired twice (unless I’m debugging or put in a pop-up). The addrow function contains no loops, just adds a row to an HTML table. The variable i remains the same for both calls, it does not get incremented:
function getAccount(val) {
var account = val.value;
if (account.length == 8) {
var i = parseInt(val.id.replace("account", ""));
$.ajax({
type: "GET",
url: "/123/AccountSelect?account=" + account,
dataType: 'json',
ContentType: "application/json, charset=UTF-8",
success: function (data) {
//create new row for next account if needed
addRow(i + 1, data);
},
error: function (xhr, status, error) {
showModal(xhr.status + ": " + xhr.statusText);
}
});
}
}
Again, it only does this if there’s no debugger running (of course) or no pop-up to interrupt the flow.
2
Answers
Here's what worked. I used a boolean to only allow the row to be added once, then used the onmouseup event of the newly created input in the new row to reset the boolean to allow for other rows to be added.
Please try to use
async: false
as following: