3

I've been trying to ensure an alert displays on a user typing in PO BOX number in the street address field on the checkout page, saying we don't ship to PO BOX.

My jQuery code doesn't seem to bind a change event to this field. The code snippet is placed in a custom JS file that loads once the DOM is ready.

Is it something possible on the checkout page since the checkout in Magento is a complex part involving Knockout JS and all that?

Any advice/help would greatly be appreciated. Screenshot explaining the requirement attached.

enter image description here

//    reject PO Boxes in first line of shipping address
    if (docloch.indexOf("checkout")>-1) {
        var poBox = /^ *((#\d+)|((box|bin)[-. \/\\]?\d+)|(.*p[ \.]? ?(o|0)[-. \/\\]? *-?((box|bin)|b|(#|num)?\d+))|(p(ost)? *(o(ff(ice)?)?)? *((bo          x|bin)|b)? *\d+)|(p *-?\/?(o)? *-?box)|post office box|((box|bin)|b) *(number|num|#)? *\d+|(num|number|#) *\d+)/i;

        $('[name="street[0]"]').change(function(){
            if ( ($(this).val()).match(poBox) !== null){
                $(this).val("");
            }
//        });   
//    } 
1

Try this instead:

$(document).on('change', '[name="street[0]"]', function(){
    if (($(this).val()).match(poBox) !== null){
        $(this).val("");
    }
});  

I suspect your problem is the Knockout HTML gets rendered after your JS, using domReady! or jQuery.ready won't really help either as the checkout is slow and usually renders several seconds after the DOM has loaded.

My fix above is to use event delegation which means your event listener will fire regardless of when the HTML was rendered.

| improve this answer | |
  • Ben, amazing. It emptied the field when PO BOX entered. I am trying to add an alert to notify the shopper that we don't server PO BOX. – CodeForGood Jun 26 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.