yogesh prajapati yogesh prajapati - 1 year ago 71
Javascript Question

Why does "greater than" comparison of numbers give unexpected result

There is an input field, like this,

<input class="form-control" type="number" name="recieved_by_quantity" id="quantity" />

Dynamically, a value is assigned to the input tag, like this,

document.getElementById('quantity').value = qu; //var qu=11 lets say

Now, what i want is, if the user manually inputs a value greater than "qu", then the value would automatically change itself to "qu".

What i did for this is something like,

document.getElementById('quantity').addEventListener("change", function() {
var qc = this.value;
if(qc>qu) {
this.value = qu;

The strange thing that is happening is if i input any value from 2 to infinity, it is changing all of them to 11. Only value it does not change are 0,1,10,100,1000,10000 and so on..
I am completely confused. Please help.

Answer Source

Use parseInt

var qc = parseInt(this.value)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download