yukinari
yukinari

Reputation: 175

Vue.js - How can I change output value if input is empty

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/

Upvotes: 4

Views: 13895

Answers (2)

CuriousGuy
CuriousGuy

Reputation: 4138

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:

  • Using v-bind : v-bind:placeholder="placeholder"
  • Using static text : placeholder="please enter your first name"

Live Demo

Upvotes: 1

Bert
Bert

Reputation: 82489

@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.

Upvotes: 6

Related Questions