4

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 Answer 1

3

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.

4
  • 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. Commented Jun 26, 2020 at 13:49
  • could you please have a look at a jQuery related post of mine. Commented Oct 11, 2020 at 9:55
  • stackoverflow.com/questions/64301831/… Commented Oct 11, 2020 at 9:56
  • Hi Ben, Since I know you're an expert in JavaScript, I'm seeking your help in finding a solution to this KnockOut JS issue with attaching an event listener/handler to reload the page. Please check my post here magento.stackexchange.com/questions/364426/… Commented Feb 10, 2023 at 11:56

Your Answer

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

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