bo1ng
bo1ng

Reputation: 21

Input Number - max constraint validation not working

I have an input field number that you can see on snippet below, this seems to work but there is a bug.

When you insert 89, it works and returns the max value as it is supposed to.

But if the first digit is under 7, it doesn't work (any number under 69). It only compares the first digit and not the final digit.

How can I use it the right way?

Thank you!

<input type="number" name="teste" id="teste"
       value="0" min="0" max="7" 
       onchange="javascript: if (this.value > this.max) this.value = this.max;" />

Upvotes: 2

Views: 1167

Answers (3)

prasad_
prasad_

Reputation: 14297

Consider the code: if (this.value > this.max) this.value = this.max;

In the function, the values of the input and the max are used and compared as text (or string data type). Your intention is to compare numbers. The example does that:

The HTML:

<body>

    Result: <p id="result">0</p>

    <input type="number" name="teste" id="teste" 
           value="0" min="0" max="7" 
           onchange="test(this)" />

    <script src="test.js"></script>

</body>


test.js:

function test(elmnt) {

    console.log(typeof elmnt.value); // this returns "string"
    console.log(typeof elmnt.max);   // this returns "string"

    // convert string numbers to integer numbers
    let intVal = parseInt(elmnt.value);
    let maxInt = parseInt(elmnt.max);

    console.log("Input: " + intVal);

    if (intVal > maxInt) {
        intVal = maxInt;
    }

    console.log("Result: " + intVal);
    document.getElementById("result").innerHTML = intVal;
}

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

HTML attributes can only contain text (no other types) so you are doing lexicographical order. Please compare:

console.log("27" > "7");
console.log(27 > 7);

Since it isn't very useful to sort numbers alphabetically, you can extract numbers from strings:

console.log("27", typeof "27");
console.log(parseInt("27", 10), typeof parseInt("27", 10));

Nowadays, second argument (radix or base) should default to 10 in most cases but setting is explicitly avoids surprises.

Upvotes: 0

BullDozer
BullDozer

Reputation: 66

Maybe convert value to integer before comparison like this:

   <input type="number" name="teste" id="teste" value="0" min="0" max="7" onchange="javascript: if (parseInt(this.value) > this.max) this.value = this.max;" />

Upvotes: 2

Related Questions