通过具有共同元素来检测输入是否匹配

时间:2013-09-03 14:45:49

标签: javascript html

我有两个输入框,我正在尝试比较它们,以便查看它们是否有共同的元素。但是出于某种原因,它无法正常工作。我的代码:

HTML:

Personal Address line 1: <input type = "text" id = "persAdd1" />
Address Line 1: <input type = "text" id = "addLine1" />
<input type = "submit" value = "Continue" onclick = "vali()" />

JavaScript的:

function vali() {
    var add1Str = document.getElementById('persAdd1').value;
    var add2Str = document.getElementById('addLine1').value;
    var arr1 = add1Str.split(" ");
    var arr2 = add2Str.split(" ");
    var arr3 = [];
    for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                arr3.push( arr1[i] );
                if(arr3 !== ""){
                    alert("error");
                }
            }
        }
    }
}

jsFiddle

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下内容适合您。

function vali() {
    var add1Str = document.getElementById('persAdd1').value;
    var add2Str = document.getElementById('addLine1').value;
    var arr1 = add1Str.split(" ");
    var arr2 = add2Str.split(" ");
    var arr3 = [];
    for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                arr3.push(arr1[i]);
                //console.log(arr3);
            }
        }
    }
    if (arr3.length > 0) { //check if the array 3 has any items, if yes alert error.
        alert("error");
    }
}

Demo