Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting form data on submit?

Tags:

vue.js

vuejs2

When my form is submitted I wish to get an input value:

<input type="text" id="name"> 

I know I can use form input bindings to update the values to a variable, but how can I just do this on submit. I currently have:

<form v-on:submit.prevent="getFormValues"> 

But how can I get the value inside of the getFormValues method?

Also, side question, is there any benefit to doing it on submit rather than updating variable when user enters the data via binding?

like image 977
panthro Avatar asked Mar 09 '17 11:03

panthro


People also ask

How do I get form values on submit?

To get form values on submit, we can pass in an event handler function into the onSubmit prop to get the inputted form values. We use the useState hook so that we can use the phone state as the value of the value prop.

How do I get form data on submit in Reactjs?

A <form> with a <button> or <input> with type=submit will get submitted when the user presses Enter in any of the form's <input type=text> . If you rely on an onClick of a button, the user must click the button or focus it and press Enter/Spacebar. Using onSubmit will enable both use cases.

How do I retrieve data from a form?

How to retrieve form data sent via GET. When you submit a form through the GET method, PHP provides a superglobal variable, called $_GET. PHP uses this $_GET variable to create an associative array with keys to access all the sent information ( form data ). The keys is created using the element's name attribute values.


1 Answers

The form submit action emits a submit event, which provides you with the event target, among other things.

The submit event's target is an HTMLFormElement, which has an elements property. See this MDN link for how to iterate over, or access specific elements by name or index.

If you add a name property to your input, you can access the field like this in your form submit handler:

<form @submit.prevent="getFormValues">   <input type="text" name="name"> </form>  new Vue({   el: '#app',   data: {     name: ''   },   methods: {     getFormValues (submitEvent) {       this.name = submitEvent.target.elements.name.value     }   } } 

As to why you'd want to do this: HTML forms already provide helpful logic like disabling the submit action when a form is not valid, which I prefer not to re-implement in Javascript. So, if I find myself generating a list of items that require a small amount of input before performing an action (like selecting the number of items you'd like to add to a cart), I can put a form in each item, use the native form validation, and then grab the value off of the target form coming in from the submit action.

like image 162
Sean Ray Avatar answered Sep 16 '22 17:09

Sean Ray