Reputation: 1183
I have a project with a input that only excepts numbers.
Inside the template I have defined a input with the value set to the variable that is being changed and the input being set to the function that checks if it is a number:
<input
:value="ie"
@input="(evt) => changeIE(evt)"
type="number"
min="0"
/>
Then in the setup function I have declared a ref ie
. This contains the actual value that is being set by the input. I also have declared the `changeIE' function. Here I first get the input text from the evt. Then I check if the last entered character is a number. If not I remove the last character from the string. The next step is to parse the string to an Integer. And lastly I set the value of the variable to the new value of the input.
const ie = ref('');
const changeIE = (evt) => {
let value = 0;
let input = evt.target.value;
let isnum = /^\d+$/.test(input[input.length - 1]);
if (!isnum) input = input.slice(0, -1);
if (input !== '') value = parseInt(input);
ie.value = value;
};
The problem is that the input keeps on excepting non numerical numbers even tough I check if they are numbers and if not I remove that character from the string.
Upvotes: 1
Views: 701
Reputation: 1
Try to use the v-model
with number as modifier and set initial value to 0 :
<input
v-model.number="ie"
type="number"
min="0"
/>
and :
const ie=ref(0)
Upvotes: 1
Reputation: 720
try
const ie = ref(null) // instead of ref('')
By default you set it to a string
Upvotes: 0