输入时检查字符是否在数组中

时间:2014-08-06 18:44:22

标签: jquery arrays string letters

我的jQuery代码有问题。

我想检查用户在输入中键入内容时字符串中的字符。

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");
        }
    }

此代码检查输入中的所有用户类型是否在数组中,但我想在信件后检查此字母。

例如:

用户类型:0 - 没关系

用户类型:00 - 仍然可以

用户类型00-340 - 它不行,现在我想显示警告,我们在数组中没有它

用户类型:3 - 没关系

用户类型:35 - 它不行,现在我想显示警告我们没有它在数组中

我将非常感谢任何提示。 此致

1 个答案:

答案 0 :(得分:0)

您可以使用jQuery.map将匹配的结果作为数组返回 - 然后检查数组大小以查看它们是否良好

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

相关问题