0

I am trying to check if the user enters at least one number. If yes, the output = 'okey' else 'no number'. This works only for the first number, however when I enter 2, the function answers 'no number'. Any ideas? thanks!

        var firstName = document.getElementById('firstName');
        var alert = document.getElementById('check');

        function nameSecurityCheck() {
            var firstNameValue = firstName.value;
            if (firstNameValue.indexOf('1' || '2') === -1) {
                alert.textContent = 'no number';
            } else {
                alert.textContent = 'okey';
            }
        }
        firstName.addEventListener('blur', nameSecurityCheck, false);
mad.mix
  • 53
  • 1
  • 2
  • 12

1 Answers1

3

Your problem is that you only check the indexOf for '1':

In particular, this statement:

'1' || '2' === '1'

Always evaluates to '1'. This means that your indexOf always checks for '1', never '2'.

You may be looking for this:

function nameSecurityCheck() {
        var firstNameValue = firstName.value;
        if (firstNameValue.indexOf('1') === -1 &&
            firstNameValue.indexOf('2') === -1) {
            alert.textContent = 'no number';
        } else {
            alert.textContent = 'okey';
        }
    }

Edit: However, since it looks like you're actually trying to check that a string contains a number, you can use a quick regex match for that:

var matches = value.match(/\d+/g);
if (matches == null) {
    alert('no number');
}
TbWill4321
  • 8,626
  • 3
  • 27
  • 25