Houy Narun
Houy Narun

Reputation: 1725

How to check input box is empty by v-model in Vue JS?

In my learning app about Vue, I bind message with the input box using v-model of vue. In that, I set another method to check if the input box is empty then I set default message value to something else by default.

This below is my snippet:

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods:{
  	check:function(){
  		if (this.message==''){
  			this.message='Please enter text in text box below';
  		}
  	}
  }
})
<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
    <!--
        v-model:
        Used with form input for user synchronize data between front-end and back-end
        as seen here message is bind with form input, so whenver we update the form, the var message
        will be updated as well
     -->
        <div id="app">
            <p>{{ message }}</p>
            <input v-model="message" v-on="check">
        </div>
        
        <script src="index.js"></script>
    </body>
</html>

However, it seemed like v-on="check" does not work as well as the input box is empty the message does not change. Is there anything I was missing?

PS: I am new to VueJS :)

Upvotes: 1

Views: 21906

Answers (2)

MartinT
MartinT

Reputation: 644

There are multiple ways to solve this issue like:

  1. Add conditional logic to your template:
<p>{{ message || 'Your default text here'}}</p>
  1. Use computed property
  2. Use filter

Upvotes: 1

Sajad Haibat
Sajad Haibat

Reputation: 717

Test it Like this:

if (this.message === '' || this.message === null || this.message.value === 0){
            this.message='Please enter text in text box below';
        }

Upvotes: 0

Related Questions