0

I have a checkout form where a zipcode is needed. I need this zipcode to get a LocationID. The zipcodes are in 0000XX format but i just need the first 4 digits. Now i have made a (global) javascript to get the locationID trough ajax.

The only problem is that now im using a keyup function that is activated when someone types in a zipcode. But i want it to be activated when a user has typed in something and clicks on another field. how can i do this ?

$('#deliveryzip').bind('keyup change', function(){

    //Get zip
    var zip = $('#deliveryzip').val();

    //Strip first 4 chars from input
    //check if 4 chars are integer
    //if all ok do ajax...

    //Get locationID from zipcode
    $.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(response){
        if(response == "ok"){
            alert(response);

            //If return is ok..
            var show = true;
        }
    });    


if(show){
    $('#locInfo').show();
} else {
    $('#locInfo').hide();
}
    return false;

 });
2
  • 1
    Your code seems to be correct, just use different events for different functionalities i.e. "keyup" for validation "change" for ajax don't combine both in one. Commented Feb 19, 2014 at 11:09
  • you can bind onblur event Commented Feb 19, 2014 at 11:11

3 Answers 3

2

Instead of listening to the keyup event, why don't you just listen to the change event?

$('#deliveryzip').on('change', function(){....});

The change event fires when an input field changed and once it looses focus (e.g. through the user clicking on another element). See http://msdn.microsoft.com/en-us/library/ie/ms536912(v=vs.85).aspx for more info (from Microsof) and here the documentation from Mozilla https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change

Sign up to request clarification or add additional context in comments.

Comments

0

You can use onBlur function : http://www.w3schools.com/jsref/event_onblur.asp

The onblur event occurs when an object loses focus.

Onblur is most often used with form validation code (e.g. when the user leaves a form field).

Tip: The onblur event is the opposite of the onfocus event.

With jQuery : on( "blur", handler )

2 Comments

Using onBlur might not ber the best solution, because the obtained location shouldn't only be showed when the focus is lost (the user clicks anywhere elöse outside the control) but just when the user finishes his input, so the onChange event seems to be more suitable
voted up.. was going for the onBlur, but did not thought about this. thank you!
0

Change 'keyup change' to blur

Blur is essentially the opposite of focus

Documentation here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.