Include doesn't work for input text in Javascript

Viewed 35

I have input field in html and I don't want the user to enter letters. I'm doing this with include method but it's not working. Here's my code:

var priceError = priceInp.value;
var abc = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "K", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

priceInp.addEventListener("change", function () {
    priceError = priceInp.value;
});

if (saveButton) {
    saveButton.addEventListener("click", function () {
        if (priceError.includes(abc)) {
            console.log("No");
        }
});
1 Answers

There are multiple ways to solve this. First you can use some array method (ES5).

if (abc.some(function(val) { return priceError.indexOf(val) >= 0; })) {
   console.log('No')
}

Arrow function would look like:

if (abc.some(val => priceError.indexOf(val) >= 0)) {
   console.log('No');
}

Don't forget to write indexOf(val) >= 0 because if you write just ìndexOf(val) first character check will not be taken into account.

Second would be regex:

if (new RegExp(abc.join("|")).test(priceError)) {
    console.log('No');
}
Related