正在查找是否存在重复的名称属性

Finding if there is a duplicate name attribute

本文关键字:属性 查找 是否 存在      更新时间:2024-02-04

假设我有以下内容;

<input type="text" id="1" name="1" value="" />
<input type="text" id="2" name="2" value="" />
<input type="text" id="3" name="3" value="" />
<input type="text" id="4" name="2" value="" />

我正在尝试使用一个函数,该函数将能够确定是否存在具有相同名称的属性。

因此,在本例中,会出现一个红色标志,表明id="4"具有重复名称属性。

我知道我必须做这样的事情,但我可能在这里拐弯抹角。你们觉得怎么样?

function findDuplicates(name) {
    var found = 0;
    $("input").each(function() { 
         if($(this).attr('name') == name)
            found++;
    });
    return found;
}

尝试jQuery属性选择器:

if(1 < $('input[name=2][type=text]').length) {
    //duplicate
}

所以你的功能看起来像:

function findDuplicates(name) {
    return $('input[name='+ name +']').length;
}

编辑

使用普通JS:

function findDuplicates(name) {
    return document.getElementsByName(name).length;
}

在某个地方创建一个空的div,假设我给了我的div一个id"return_value"。

<script>
function validate(){
    var name1 = document.getElementById("1").value;
    var name2 = document.getElementById("2").value;
    var name3 = document.getElementById("3").value;
    var name4 = document.getElementById("4").value;
    var error = '';
    error = (name1 == name2 || name1 == name3 || name1 == name4 || name2 == name3 || name2 == name4 || name3 == name4) ? 'Duplicate Entry!' : 'Data OK!';
    getElementById("return_value").innerHTML = error;
}   
</script>

你只需要让你的表单onsubmit调用Javascript函数来进行比较,如果你想在数据有效的情况下提交表单,你可以使用AJAX来完成。之前的海报是正确的,因为如果没有更多关于你想要做什么的信息,很难回答这个问题。

var found = 0;
var array = new Array(); //create new array
$( "input[type=text]" ).each(function( index ) {
    var name = $(index).attr('name'); //get name of current element
    if(array.indexOf(name) == -1) //check if name doesn't exist in array
    {
      array.push(name); //if true, add it to the array
    } else {
      found++; //if it exists, increment found
      var duplicate = $(index).attr('id'); //get the id of the current element
      console.log('Input with Id = ' + duplicate + ' has a duplicate name attribute');
    }

});

如果长度减去1,则可以返回0表示没有重复项。

我还会传入元素和属性名称,以实现完全的可重用性。

function hasDuplicates(el, attr, value) {
    return $(el + '[' + attr + '=' + value + ']').length - 1;
}

其他答案要求您知道要查找的属性的名称,这是没有意义的,如果他知道输入字段的名称,他可以在浏览器中查看源代码,并查看是否找到了两个同名元素。

使用以下代码,您可以将其复制并粘贴到浏览器的控制台窗口中:

var found = 0;
var array = new Array(); //create new array
$("input[type=text]").each(function( index ) {
    var name = $(index).attr('name'); //get name of current element
    if(array.indexOf(name) == -1) //check if name doesn't exist in array
    {
         array.push(name); //if true, add it to the array
    } else {
         found++; //if it exists, increment found
         var duplicate = $(index).attr('name'); //get the name of the duplicate element
         console.log('Input with Name => ' + duplicate + ' has a duplicate name attribute');
    }
});