遍历 Input检测是否有重复的值

在项目中需要遍历某个Table中的Input输入是否有重复的值,为此基于Jquery写了两种实现方式(关键在于取值方式):

方法1:

function CheckGoodsNo() {
    var ishidegoodsno = $('#cbxAutoCreate').attr('checked');
    if (ishidegoodsno) {//自动生成货品编号,跳过货品编号检测
        return true;
    }
    var ary = new Array()
    try {
        $("input[name='code']").each(function () {
            if ($(this).val() == "") {
                $(this).focus();
                alert('货品编号不能为空');
                throw '货品编号不能为空';
            }
            else {
                ary.push($(this).val());
            }
        });
        $("input[name='code']").each(function () {
            var val = $(this).val();
            var j = 0;
            for (var i = 0; i < ary.length; i++) {
                if (ary[i] == val) {
                    j++;
                    if (j > 1) {
                        j = 0;
                        $(this).focus();
                        alert('货品编号不能重复');
                        throw '货品编号不能重复';
                    }
                }
            }
        })
    }
    catch (e) {
        return false;
    }
    return true;
}

方法2:

//获取商品编码
var NoRepeat_Error = "";
function NoRepeat() {
    var is_ok = true;
    var GNOS = "";
    $("#sell-body").find('tr').each(function() {
        //console.log($(this).html());
    //console.log($("input", this).val());
        
        $(this).find('td').each(function() {
            //console.log($(this).html());
            //console.log($("input", this).attr("name"));
            if ($("input", this).attr("name") == "code") {
                //console.log($("input", this).val());
                if ($("input", this).val().indexOf("#") != -1) {
                    alert("货品编号不允许有特殊符号!");
                    is_ok = false;
                    return false;
                } else {
                    GNOS += $("input", this).val() + ",";
                }
            }
        })

    })
    if (is_ok) {
        is_ok= VeriGoodsRepeat(GNOS);
    }
    return is_ok;
}

//
function VeriGoodsRepeat(gnos) {
    var is_Ok = true;
    NoRepeat_Error = "";
    var g_arrary = gnos.split(',');
    for (i = 0; i < g_arrary.length; i++) {
        var i_Part = g_arrary[i];
        var i_Count = 0;
        if (i_Part != null && i_Part != "") {
            for (y = 0; y < g_arrary.length; y++) {
                if (i_Part == g_arrary[y]) {
                    i_Count++;
                }
            }
            if (i_Count > 1) {
                //alert(i_Part + ":不可重复!");
                NoRepeat_Error = "货品编号:["+ i_Part + "]:不可重复!";
                is_Ok = false;
            }
        }
        
    }
    return is_Ok;
}
原文地址:https://www.cnblogs.com/PLifeCopyDown/p/6002723.html