I want to bind an input with a model. When the page loads, the input has a value. But when I bind with a model, it gets empty as I initialize the model with a null or empty value.
<div id="update-email">
<input type="text" name="email" value="[email protected]" v-model="email">
{{ email }}
</div>
JavaScript:
new Vue({
el: '#update-email',
data() {
return {
email: '',
};
}
});
jsfiddle: https://jsfiddle.net/Debiprasad/v8wyj2kw/
How can I update email
value with the value of the input when it loads?
I handle this by initializing my model value to the value of the input field. This way when the vue initially sets the input field the model value, it's the value that was in the input field.
Example below using jquery:
<div id="update-email">
<input id="email" type="text" name="email" value="[email protected]" v-model="email">
{{ email }}
</div>
Javasacript:
new Vue({
el: '#update-email',
data() {
return {
email: $('#email').val(),
};
}
});
If you want to do it without jquery, just change $('#email').val()
to document.getElementById('email').value
You can use a directive to put the value into the element and issue an input event.
new Vue({
el: '#update-email',
data: {
email: null
},
directives: {
init: {
bind(el) {
el.value = el.getAttribute('value');
el.dispatchEvent(new Event('input'));
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="update-email">
<input v-init type="text" name="email" value="[email protected]" v-model="email"> {{ email }}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With