William Kennedy
William Kennedy

Reputation: 143

How to detect if the first number of my input is a specific number?

I need to verify if the first number of the input is 5 or 4.

My HTML:

<input type="text" id="first_six_digits" name="first_six_digits">

I've tried this:

$('#first_six_digits').on('keypress', function (e){
    var first = this.value.charAt(0),
        master = false,
        visa = false;

    switch(first){
        case e.keyCode == 53:
            master = true;
            alert('master');
            break;

        case e.keyCode == 52:
            visa = true;
            alert('visa');
            break;
    };
});

I don't know how to compare the first number var first = this.value.charAt(0) to e.keyCode == 53.

Upvotes: 0

Views: 135

Answers (3)

Caal Saal VI
Caal Saal VI

Reputation: 302

How about you just check like this ?

$('#first_six_digits').on('keyup', function (e){
    var first = this.value.charAt(0),
        master = false,
        visa = false;
    //check what is the first value
    switch(first){
        case '6':
            master = true;
            alert('master');
            break;

        case '5':
            visa = true;
            alert('visa');
            break;
    };
});

Live Demo

Upvotes: 0

HankScorpio
HankScorpio

Reputation: 3651

That's not how to write a switch. Your condition must be inside the switch() part, and each case should be a constant value to compare against the condition, not a comparison.

Also, charAt() returns a character, not a keyCode.

    switch(first){
        case '5':
            master = true;
            alert('master');
            break;

        case '4':
            visa = true;
            alert('visa');
            break;
    };

Upvotes: 1

Alex Maroz
Alex Maroz

Reputation: 55

Instead of

case e.keyCode == 53:

use

case '5':

Upvotes: 1

Related Questions