I'm new to vue.js. I want to change the output text to the same string that's in placeholder if input value is empty. Here is my desired code
<div id="form">
<input class="input-f" type="text" placeholder="please enter your first name" v-model="firstName">
<input class="input-l" type="text" placeholder="please enter your last name" v-model="lastName">
<div class="output">
<p class="f">{{firstName}}</p>
<p class="l">{{lastName}}</p>
</div>
vuejs with jquery
(function(window) {
var data = {
firstName: "Stack",
lastName: "Overflow",
}
var vm = new Vue({
el: "#form",
data: data,
watch: {
firstName: function(v) {
if (!v) {
$(".f").text($(".input-f").attr("placeholder"))
}
},
lastName: function(v) {
if (!v) {
$(".l").text($(".input-l").attr("placeholder"))
}
}
}
})
})(window)
Also, if I leave the input box empty, the data won't bind again. Please tell me how can I achieve it? https://jsfiddle.net/je491vas/
@charith was most of the way there. You should add your placeholder text to your data and then bind it to your inputs and show it in your output if the matching data isn't available.
let data = {
firstName: "",
lastName: "",
lastNamePlaceHolder: "please enter your last name",
firstNamePlaceHolder: "please enter your first name"
}
new Vue({
el:"#form",
data
})
Template
<div id="form">
<input class="input-f" type="text" :placeholder="firstNamePlaceHolder" v-model="firstName">
<input class="input-l" type="text" :placeholder="lastNamePlaceHolder" v-model="lastName">
<div class="output">
<p class="f">{{firstName || firstNamePlaceHolder }}</p>
<p class="l">{{lastName || lastNamePlaceHolder}}</p>
</div>
</div>
Example.
Hope that you want to set the placeholder text if the input text is empty. This works by default and you do not need to write any additional logic. This is the behaviour of placeholder.
Please refer the code below :
<div id="form">
<input class="input-f" type="text" placeholder="please enter your first name" v-model="firstName">
<input class="input-l" type="text" v-bind:placeholder="placeholder" v-model="lastName">
<div class="output">
<p class="f">{{firstName}}</p>
<p class="l">{{lastName}}</p>
</div>
</div>
(function(window) {
var data = {
firstName: "",
lastName: "",
placeholder:"please enter your last name"
}
var vm = new Vue({
el: "#form",
data: data
})
})(window)
You can define the placeholder in either of the above ways:
v-bind:placeholder="placeholder"
placeholder="please enter your first name"
Live Demo
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