skip to Main Content

I need to set #billing-postcode to a certain value, via a JS script.

If I go on the checkout page and write

jQuery('#billing-postcode').val('2222')

I see the input with the value 2222 and the Postcode label on top of it. If I click the postcode input, the value gets cleared.

I’ve tried adding to the parent the is-active class, which solved the issue of showing the label on top of the value in the field, but the second I click on the input it gets cleared.

When I check the DOM, there is no value set so I’ve added the attribute value with 2222 and this time it stays there.

The issue is not gone, as if I submit the form, the postcode gets emptied and the value lost.

I also tried to POST to /wp-json/wc/store/v1/batch?_locale=user, path /wc/store/v1/cart/update-customer which indeed keeps the value on refresh, but then again, if I change the value from the console, once again, not it flickers between the old value and the new value.

[UPDATE] I just turned off all the event listeners on all input fields and that solves my issue, BUT it creates another few… no more live validation, countries dropdown not working etc.

Is there anyone who had this issue and found a fix?

**With a fresh WP installation, fresh Woocommerce, no other plugins and the default theme, the field value doesn’t get filled.
**

  • adding is-active class to the parent
  • post value to /wp-json/wc/store/v1/batch?_locale=user
  • remove all event listeners
  • set the value via attribute

2

Answers


  1. Use a different method to set the value of the input field. Instead of directly setting the value using jQuery’s .val() method, you can try using the setAttribute method to set the value attribute of the input field. This way, the value should stay in the field even if there are event listeners or validation scripts attached to it.

    Here’s an example of how you can set the value using the setAttribute method.

    document.getElementById('billing-postcode').setAttribute('value', '2222');

    This should set the value of the input field without triggering any event listeners or validation scripts that might be causing the issue.

    Login or Signup to reply.
  2. If you’re using checkout block, try

    wp.data.dispatch('wc/store/cart').setShippingAddress({'postcode':12345 });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search