HTML Input Type="Number" Still Returning a String When Accessed from JavaScript

HTML input type=number still returning a string when accessed from javascript

It's normal you get a string.

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes. For example the email type will show a keyboard with the @ and '.' on the keyboard and number will show a numeric keyboard.

Handle onChange on input type=number

Based on this:

The purpose of the number type is that mobile browsers use this for showing the right keyboards and some browsers use this for validation purposes.

To fix this, there is some approaches. But I suggest to you to parseInt the value when onChange. So:

  const [value, setValue] = useState(1);

const handleChange = (e) => {
setValue(parseInt(e.target.value));
};
const handleAdd = () => {
setValue((prev) => prev + 1);
};
const handleSubtract = () => {
setValue((prev) => prev - 1);
};

return (
<div>
<input type="number" value={value} onChange={handleChange} />
<button label="+" onClick={handleAdd} />
<button label="-" onClick={handleSubtract} />
</div>
);

Getting a string instead of expected number from Angular template and input native element's value

It is written on the spec that value will always be stored as string. So even if you set the input type as number, it only update the user interface. But the value is still the same in string type.

I don't extract the data the same way with you. Not sure if you have any reason for doing so. I always use the ngModel directive.

Basically it is the two way binding, if you update the data model, it will update the UI and the other way around. So that you don't have to get the value manually through the ElementRef as you did on the question. It is done automatically for you.

app.component.html

<input type="number" [(ngModel)]="inputVal" (keyup)="onKeyUp($event)">

app.component.ts

onKeyUp(event: KeyboardEvent) {    
console.log(this.inputVal);
}

Noted the type="number" on the HTML code. When you set it like that, the inputVal will be return as a number. I didn't really check the source code but probably Angular will parse it automatically somehow.

If you don't put it, the value will still be keep as a string.

I prepare the example for it. Please check https://stackblitz.com/edit/angular-ngmodel-number

You can just type into the input and see the value and the type.

number input.value returns empty string if it contains e character

e stands for exponential, it is a valid character for number. This is happening because you have set input type to number. You can try this

Please check this thread
https://stackoverflow.com/a/31706796/5238397

HTML text input allow only numeric input

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.

JavaScript

Try it yourself on JSFiddle.

You can filter the input values of a text <input> with the following setInputFilter function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):

// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter, errMsg) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
textbox.addEventListener(event, function(e) {
if (inputFilter(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
this.classList.remove("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
this.classList.add("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
});
}

You can now use the setInputFilter function to install an input filter:

setInputFilter(document.getElementById("myTextBox"), function(value) {
return /^\d*\.?\d*$/.test(value); // Allow digits and '.' only, using a RegExp
}, "Only digits and '.' are allowed");

Apply your preferred style to input-error class. Here's a suggestion:

.input-error{
outline: 1px solid red;
}

See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!

TypeScript

Here is a TypeScript version of this.

function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean, errMsg: string): void {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
this.value = this.oldValue;
if (this.oldSelectionStart !== null &&
this.oldSelectionEnd !== null) {
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
} else {
this.value = "";
}
});
});
}

jQuery

There is also a jQuery version of this. See this answer.

HTML 5

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:

  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsers don't support the step, min and max attributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

Try it yourself on w3schools.com.

How can I set max-length in an HTML5 input type=number element?

And you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

Sample Image

How to set maximum length in input type=number?

max attribue specifies the maximum possible value that we can specify.

for more details see this link

I think the following will be helpful to you,

//maxlength="10"
<input type="number" onKeyPress="if(this.value.length==10) return false;" />


Related Topics



Leave a reply



Submit