HTML Input Values are Treated as Strings by Default

If you use a input and grab the value inside from it, the value, even if it's a number will be converted to a string.

One way to solve this problem is add parseInt or parseFloat to the values.

Playgrond

This is supposed to be a calculater, however, the results are worng since javascript treats even number inputs as numbers. 

input1:
input2:

Result:
Also this can cause problems when using Vue v-modal and vue methods when data is supposed to be a number which needs to react to both the v-model and method. 

Example

Click the "add" button then click the input up or down arrow to change input value, then click the "add" button again to see the effect.
<div id="app">
  {{ count }}
  <br />
  <input type="number" v-model="count" />
  <br />
  <button v-on:click="add">Add</button>
</div>
<script>
var app = new Vue({
  el: '#app',
  data: {
    count: 1
  },
    methods:{
       add:function(){
       	   this.count += 1
       }
    }
});
</script>
{{ count }}

Solution

One way to solve this problem is to add parseInt or parsrFloat for the data in the method function. Or use ++ instead of +=1 for this.count
<div id="app">
  {{ count }}
  <br />
  <input type="number" v-model="count" />
  <br />
  <button v-on:click="add">Add</button>
</div>
<script>
var app = new Vue({
  el: '#app',
  data: {
    count: 1
  },
    methods:{
       add:function(){
       	   this.count ++   
           // or this.count = parseInt(this.count) + 1
    }
});
</script>
{{ count }}

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser