Robin Aegerter
Robin Aegerter

Reputation: 467

Show string in input field type=number

Is it possible to show a string within an input field of the type number?

I want to do something like this:

<input value="4'000" placeholder="Type some numbers" type="number" />

It will always show the placeholder because "4'000" has an apostrophe and is, therefore, a string.

Any ideas on how to show a string (if possible without package - I'm using React) inside a number typed input?

Thanks!

Upvotes: 1

Views: 2471

Answers (3)

Not A Robot
Not A Robot

Reputation: 2684

It will be much better to use input type as number for the values which are rational/integers but not strings.

So in your case, you can use text as an input field for better readability and in javascript you can convert that string to a number.

let num = document.getElementById("some-number").value;

num = num.replace(/\'/g,'');
num = parseInt(num,10);

console.log(num);
<input type="text" value="4'000" id="some-number" />

Upvotes: 1

I am L
I am L

Reputation: 4632

So before you add the value on your value field, what you can do is "process" it first to remove all non numeric stuff on the value:

use this function: \D is a shorthand regex that matches all non-digit.

const stripNonNumeric = str => str.replace(/\D/g,'');

(If you are using state)

const [val, setVal] = useState(stripNonNumeric(props.defaultValue));

const onChangeValue = (e) => {
   // this should be unnecessary if the field is already type="number",
   // but if its not then this use this, else just use e.target.value
   const value = stripNonNumeric(e.target);

   setVal(value);
};

return <input type="number" value={val} onChange={onChangeValue} />;

If you are getting your value from somewhere else:

const value = props.valFromSomewhere;

return <input type="number" value={stripNonNumeric(value)} />;

Upvotes: 1

eux
eux

Reputation: 3282

From WDN Web Docs input type="number"

input elements of type number are used to let the user enter a number. They include built-in validation to reject non-numerical entries.

Sou you can't show a string inside a number typed input.

But you could transform "4'000" to '4000', and show it as a number:

"4'000".replaceAll("'", "") // => "4000"

<input value="4000" placeholder="Type some numbers" type="number">

Upvotes: 1

Related Questions