0

My code isn’t working, I’d like letters to turn green and numbers to turn red...

const inpout = document.querySelectorAll('input');

for (const type of inpout) {
  type.addEventListener('input', function() {
    const res = parseInt(this.value);
    if (typeof res === 'number') {
      this.style.color = ('red');
    } else if (isNaN(res)) {
      this.style.color = ('green');
    } else {
      this.style.color = ('green');

    }
  });

3
  • what about a alphanumeric value in the input ? eg ABC123XYZ Commented Sep 22, 2019 at 20:18
  • @joyBlanks this should be a string I guess Commented Sep 22, 2019 at 20:41
  • See w3schools.com/jsref/prop_style_color.asp this.style.color = String Commented Sep 22, 2019 at 20:44

3 Answers 3

1

ParseInt will parse a alphanumeric value to a number if it starts with a number, Just add a + infront of the value and it will be either NaN or a number

const input = document.querySelectorAll('input');
for (const type of input) {
  type.addEventListener('input', function() {
    const res = +this.value;
    if (isNaN(res)) {
      this.style.color = ('green');
    }else if (typeof res === 'number') {
      this.style.color = ('red');
    } else {
      this.style.color = ('green');
    }
  });
}
<input /><input /><input /><input />

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! It works! Thanks for the clear explaination and congrats for your ingenuity!
0

Try this, although I'm not sure if it is want you want:

working example: https://jsfiddle.net/1sfmrct8/

const inputs = document.querySelectorAll('input');

for (const element of inputs) {
  element.addEventListener('input', function(e) {
    const res = e.target.value[e.target.value.length - 1]
    if (isNumeric(res)) {
      this.style.color = ('red');
    } else {
      this.style.color = ('green');
    }
  })
}


function isNumeric(str) {
  return /^\d+$/.test(str);
}

Comments

0

In both numbers and strings inputs, values are always strings.

I think that's why your code isn't working, so another (and maybe simpler) solution would be to check input.type instead of input.value. Something like this:

if (this.type === "number") {
  this.style.color = ('red');
} else {
  this.style.color = ('green');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.