【问题标题】:Check is character is in array while typing键入时检查字符是否在数组中
【发布时间】:2014-09-29 19:53:22
【问题描述】:

我的 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 - 不行,现在我想显示警告,我们在数组中没有它

我将非常感谢任何提示。 问候

【问题讨论】:

    标签: jquery arrays string letters


    【解决方案1】:

    您可以使用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

    【讨论】:

    • 非常感谢!完美运行!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2017-03-17
    • 2013-02-06
    • 1970-01-01
    • 2019-05-13
    • 2020-07-27
    • 2010-11-07
    相关资源
    最近更新 更多