I oftenly need to debug my form inputs
I hate having to do this huge & long and sometimes missing vars ...
console.log(this.type, this.name, this.url, this.timezone, this.startDate, this.endDate, this.startTime, this.endTime, and 10 more variables .... )
Is there a way to console.log(ALL inputs in a form) ?
I've tried
getAllData(id) {
let myForm = document.getElementById(id)
let formData = new FormData(myForm)
const data = {}
// need to convert it before using not with XMLHttpRequest
for (let [key, val] of formData.entries()) {
Object.assign(data, { [key]: val })
}
console.log(data)
},
and call it like so :
this.getAllData('form')
I got this in my console
I can't make sense from any of it...
Try # 2
I've tried
getAllData(id) {
let myForm = document.getElementById(id)
console.log(
Array.from(myForm.elements).map((e) => {
return e.value
})
)
},
I get better result now, but I would like to see the key along with the value.
This is what I see now.. (only the value)
CodePudding user response:
How about scoping your form values in a form
value, i.e:
data: () => ({
form: {
errors: {},
values: {
type: '',
name: ''
}
}
})
You can then simply do console.log(this.form)
, or plop <pre>{{ form }}</pre>
in the template for a JSON output.
Additionally, if you add values
and errors
within the form
value you can do your validation then contain things when outputting, i.e
<div >
<label for="input-type">Type</label>
<input id="input-type" v-model="form.values.type" type="text" : placeholder="Enter the type of the thing...">
<div v-if="form.errors.type" >
{{ form.errors.type }}
</div>
</div>
CodePudding user response:
You can also use vanilla JS for that, let's say you have the following HTML:
<form id="myform">
<input name="input-1" type="text"/>
<input name="input-2" type="text"/>
<button type="submit">Hello</button>
</form>
and then plain JS
var myForm = document.getElementById('myform');
myForm.addEventListener('submit', (event) => {
event.preventDefault();
console.log(Array.from(myForm.elements).map((el) => {
return `${el.name}: ${el.value}`; // if you have name attribute on inputs
}))
});
Example on jsbin: https://jsbin.com/tixiduzuyi/edit?html,js,console,output
Solution based on HTMLFormElement.elements, so if you have a <form>
element you could have access to all your .elements
whiting that form, you can also filter by input
type, in order to exclude buttons or checkboxes (if needed).