Fred K
Fred K

Reputation: 13910

Submitting a form only after filling a field in Vue

I'm building a Vue app. When I click the button in the form I want to fill the input with value paypal and then submit the form. But from test_form.php (it's the file action of the form) the variable $_POST['paymentMethod'] contains null instead of paypal! Where I'm wrong?

Here is the code I'm using:

HTML:

<form action="test/test_form.php" method="POST" ref="form">
  <button type="button" v-on:click="setMethod('cc')">Credit card</button>
  <button type="button" v-on:click="setMethod('paypal')">Paypal</button>
  <input type="text" name="paymentMethod" required v-model="selectedMethod">
</form>

Javascript:

new Vue({
  el: "#app",

  data: {
    selectedMethod: null,
  },

  methods: {

    // Set payment
    setMethod: function(type) {
      this.selectedMethod = type; // Here I fill the field
      this.$refs.form.submit(); // Then I submit the form
    },
  }

});

Upvotes: 1

Views: 915

Answers (1)

PatrickSteele
PatrickSteele

Reputation: 14677

Try using Vue's nextTick method to defer your form post until after the DOM has been updated:

  if (type == 'paypal'){
    var me = this;
    Vue.nextTick(function() {
        me.$refs.form.submit();
    });
  }

Upvotes: 4

Related Questions