0

I have an issue on our checkout, where we are using jQuery to add a class to the input fields, when they aren't empty. The code has worked perfectly for our needs so far. The issue now is, that we are using a small plugin that automatic provides the city name, when the zip code is entered. When this happens, the code does not work and the class is not added to the field, until it is clicked.

I can't seem to find a proper solution for this, so any help is appreciated.

$('.input-text').each(function(){
    changeState($(this));
});
$('.input-text').on('focusout', function(){
    changeState($(this));
});
function changeState($formControl){
        if($formControl.val().length > 0){
        $formControl.addClass('has-value');
    }
    else{
        $formControl.removeClass('has-value');
    }
}

Edit - plugin code:

$( document ).ready( function () {
        $( '#billing_postcode, #shipping_postcode' ).on( 'keyup', function () {
            var $input = $( this );
            var value = $input.val().trim();
            if ( value.length === 4 ) {
                var form_type = $input.attr( 'name' ).split( '_' )[0];
                update_city_by_postcode( value, form_type );
            }
        });
    } );
5
  • 1
    Does this plugin have an event that you can respond to? Currently you're updating on the focusout event. You can also update on any event exposed by the plugin, or even just try the change event that may be triggered by the plugin. Commented Nov 21, 2019 at 11:31
  • Note you can use $formControl.toggleClass('has-value', $formControl.val().length > 0) Commented Nov 21, 2019 at 11:48
  • I have shared the plugin code. I have tried the change event, but it doesn't seem to work. Commented Nov 21, 2019 at 12:22
  • @MathiasBeck: Is update_city_by_postcode synchronous? Can't you just call changeState after that? Commented Nov 21, 2019 at 12:33
  • I have tried, but can't get it to work. Can you give me an example? I am not the best at code. Commented Nov 21, 2019 at 12:48

1 Answer 1

1

If this is modifying the values of your inputs:

update_city_by_postcode( value, form_type );

Then you can just re-run your existing logic afterward:

update_city_by_postcode( value, form_type );
$('.input-text').each(function(){
    changeState($(this));
});
Sign up to request clarification or add additional context in comments.

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.