Hacker News new | ask | show | jobs
by heigh 693 days ago
For what it's worth the issue I encountered is this, and now, I am wondering if the ticket should actually be directed to jQuery, rather than Firefox...

The bug is actually around a type="number" input field, not a number in an INPUT field. But here goes my summary of it:

<!-- HTML Code //--> <input type="number" id="progress" class="form-control mr-0 pr-0" placeholder="Progress (%)" />

//JS Code $('#progress').on("change",function() { let val = $(this).val().replace(/[^0-9.]/g, '');

        // Ensure only one decimal point
        let parts = val.split('.');
        if (parts.length > 2) {
            val = parts[0] + '.' + parts.slice(1).join('');
        }

        let numVal = parseFloat(val) || 0;

        if (numVal > 100) {
            numVal = 100;
        } else if (numVal < 0) {
            numVal = 0;
        }

        $(this).val(numVal === 0 ? '' : numVal);
    });
//Expectation OnChange, it removed everything except valid numbers (including a single decimal place).

//Reality It does this for the first iteration, but not further iterations

//Example 1. Enter "1234.456AB" into the progress field (excluding the quotation marks). 2. blur from the field to trigger the onChange. 3. Observe that it works and produces the result 100 (as per the code). 4. Type in ABCD into the progress field 5. Nothing happens. ABCD remains there.

2 comments

A great way to make the bug report better would be to remove jQuery from the equation and see if it still repros. The smaller the test case the better.
Also, how I knew it's a bug? I changed type="number" to type="text" and my code worked as expected.
I think the behaviour you're describing is that a non-numeric value in a number field doesn't trigger the change event in JavaScript. I don't know if it would necessarily be a bug, but a difference in behaviour between Firefox and Chrome. In trying it with the JavaScript querySelector instead, it looks like Chrome restricts the input on keypress, whereas Firefox restricts it ahead of the change event. You could always use the keypress event, but looking at your snippet, it looks like you could just use the min and max attributes of the number field instead?