Hey I have a short question. I am learning JS (Vue.js) at the moment and now I have an example, where I have some inputs with the same class name.
<input class="checkInput" placeholder="firstname"/>
<input class="checkInput" placeholder="lastname"/>
<input class="checkInput" placeholder="age"/>
<button @click="saveData">Save</button>
Now when i click on the save button I trigger a method, which gives me an HTML Collection of all inputs with the checkInput class.
var val = document.getElementsByClassName("checkInput");
Now I want to iterate over this collection and check if one of the input values is empty.
for (let item of val) {
var y = item.value;
if (y=="") {
//Do save
} else {
//Empty Input Message to the user
}
}
The problem is, that when for example the second input is empty and I click the save button, it executes the save method either because it checks every element step by step. How can I check the whole HTMLCollection at first and then execute the method? (And no I do not want to use a form)
One of the ways you can do that in Vue.js
new Vue({
el: '#demo',
data() {
return {
user: {
first_name: '',
last_name: '',
age: null
}
}
},
methods: {
saveData() {
for (const [key, value] of Object.entries(this.user)) {
if (!value) return alert(`${key} empty`)
console.log(`${key}: ${value}`);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<input class="checkInput" placeholder="firstname" v-model="user.first_name" />
<input class="checkInput" placeholder="lastname" v-model="user.last_name" />
<input class="checkInput" placeholder="age" v-model="user.age" />
<button @click.prevent="saveData">Save</button>
</div>