How to bind an event handler to ‘street[0]’ input on the checkout page?

The question:

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.

How to bind an event handler to 'street[0]' input on the checkout page?

//    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;

            if ( ($(this).val()).match(poBox) !== null){
//        });   
//    } 

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Try this instead:

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

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.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment