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?
You have to define a model for your input.
<input type="text" id="name" v-model="name">
Then you you can access the value with
this.name
inside yourgetFormValues
method.This is at least how they do it in the official TodoMVC example: https://vuejs.org/v2/examples/todomvc.html (See
v-model="newTodo"
in HTML andaddTodo()
in JS)The form
submit
action emits asubmit
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: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.You should use model binding, especially here as mentioned by Schlangguru in his response.
However, there are other techniques that you can use, like normal Javascript or references. But I really don't see why you would want to do that instead of model binding, it makes no sense to me:
As you see, I put
ref="my_input"
to get the input DOM element:I made a small jsFiddle if you want to try it out: https://jsfiddle.net/sh70oe4n/
But once again, my response is far from something you could call "good practice"