sideroxylon
sideroxylon

Reputation: 4416

Only allow number to be entered once in input

Is there any way of using javascript/jquery to prevent a user entering the same number twice in an input box? The user can enter as many numbers as they want (one at a time), but I need to alert the user/take other action if they try to enter the same number a second time. I have tried creating an array:

 function history() {
 var numbers = [];
 numbers.push(document.getElementById('inputBox').value);
 }  

and then running:

 var n = document.getElementById('inputBox').value;
 if ($.inArray(n, numbers)> -1) {
   // alert, do something
 }

but the new array ('numbers') never gets populated by the user input, so the if clause never fires.

Upvotes: 0

Views: 356

Answers (2)

federicot
federicot

Reputation: 12341

Something like this, perhaps? I assume you are using jQuery because of the $.inArray in your code.

var numbers = [];
$('#inputBox').change(function () {
    if ($.inArray($(this).val(), numbers)) {
        // Alert the user/take other action
    } else {
        // Otherwise, add it to the array of numbers
        numbers.push($(this).val());
    }
});

It would be better if there was a button the user had to click to add the new number. Otherwise, it will be quite annoying.

Upvotes: 1

doogle
doogle

Reputation: 3406

It looks like your numbers variable is scoped to the history() function, so the numbers variable instanced that is being set is only accessibly by the history() function. This code will accomplish what you're trying to do without a global numbers variable and prevents any duplicate numbers from being entered by intercepting and canceling the key event.

$("#inputBox").on("keydown", function(e) {
    var numbers = $(this).val();
    var c = String.fromCharCode(e.keyCode);
    return ~numbers.indexOf(c);
});

Upvotes: 1

Related Questions