Search code examples
jqueryarraysstringletters

Check is character is in array while typing


I have a problem with my jQuery code.

I want to check characters from strings which is in array while user typing something in the input.

var postcodes = ["00-240","80","32","90","91"];

$('input[name="text-391"]').keyup(function(){
    var header = $('#postalcode').val();

    if($('input[name="text-391"]').val().length > 1) {
        if($.inArray(header, postcodes) > -1){
            alert("None");
        }
    }

This code checks that all what user type in the input is in array, but i want to check this letter after letter.

For example:

user types: 0 - it's ok

user types: 00 - it's still ok

user types 00-340 - it's not ok and now I want to display warning that we haven't it in the array

user types: 3 - it's ok

user types: 35 - it's not ok, and now i want to display warning that we haven't it in the array

I will be very grateful for any tips. Regards


Solution

  • You can use jQuery.map to return matched results as an array - then check the array size to see if they are good or not

    var postcodes = ["00-240","80","32","90","91"];
    $('#test').keyup(function(){
        var val = this.value;// get current value in textbox
        // use map to get all the ones that matches
        var m =  $.map(postcodes,function(value,index){
           // regex object to match on - must start with the current value
           var reg = new RegExp('^'+val+'.*$')
           // return values that matches the current value 
           return value.match(reg);
        });
    
        // display valid if input has at least one character
        // and if there is at lease 1 match 
        // (m.length will be 0 if there are no matches)
        // else display invalid
        $('#msg').text(m.length && val.length ? 'VALID':'INVALID');
    });
    

    EXAMPLE