Reputation: 3
hey i trying to figure it out what is wrong in code, i am using text box which checks the value entered is available in database or not (through onchange event) if value is not available it as to give the alert("Invalid Number");
As the code works fine when i open it first time once i refresh it gives me the 2 times alert massage.
here is my code:
$(document).ready(function(){
$(document).on('change','#acccno', function () {
var acno = $(this).val();
var data={"acno":acno,"acccno":1};
$.ajax({
url:"accsav.php",
async: false,
type:"POST",
data:data,
success:function(dat){
if(dat===''){
alert("Invalid Number");
$("#acccno").val('');
// $("#acccno").focus();
} else {
$("#image1").html(dat);
}
},
error:function(er){
console.log(er);
}
});
});
});
Upvotes: 0
Views: 156
Reputation: 175
Its really a simple change that needs to be done. Once success you empty the value in the input box. Which triggers another on change event and the ajax is called again but this time with empty values. Inside the on change function you can check if the value is empty. Please find the fixed version below
$(document).ready(function(){
$(document).on('focusout','#acccno', function () {
var acno = $(this).val();
var data={"acno":acno,"acccno":1};
if( acno !=''){
$.ajax({
url:"accsav.php",
async: false,
type:"POST",
data:data,
success:function(dat){
if(dat===''){
alert("Invalid Number");
$("#acccno").val('');
// $("#acccno").focus();
} else {
$("#image1").html(dat);
}
},
error:function(er){
console.log(er);
}
});
}
});
});
Upvotes: 0
Reputation: 15958
When the given account number is invalid it displays the alert message and changes the input to empty string, which triggers the event again and shows the alert again in this case, because the server response with an empty account number is probably also invalid. Then it changes the value again, but because it was already empty before nothing changes here and the event does not get fired again.
My suggestion: Wrap the field with a form and use the onsubmit event instead.
Upvotes: 1
Reputation: 64
you can bind the event to the specific element and not to the whole document, which is recommended anyway, or maybe you can try using "input" event.
quote from this site: https://developer.mozilla.org/en-US/docs/Web/Events/change
The change event is fired for
<input>
,<select>
, and<textarea>
elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.
Upvotes: 0