/ / Sprawdzanie, czy istnieje duplikat nazwy atrybutu - javascript, jquery

Znalezienie duplikatu atrybutu nazwy - javascript, jquery

Powiedzmy, że mam następujące;

<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="" />

Próbuję mieć funkcję, która będzie w stanie dowiedzieć się, czy istnieje atrybut o tej samej nazwie.

W tym przykładzie pojawi się czerwona flaga id="4" ma zduplikowany atrybut nazwy.

Wiem, że muszę coś takiego zrobić, ale być może biję się tutaj wokół buszu. Co wy myślicie

function findDuplicates(name) {
var found = 0;

$("input").each(function() {
if($(this).attr("name") == name)
found++;
});

return found;
}

Odpowiedzi:

4 dla odpowiedzi № 1

Wypróbuj selektor atrybutów jQuery:

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

Twoja funkcja będzie wyglądać następująco:

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

EDYTOWAĆ

Ze zwykłym JS:

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

0 dla odpowiedzi nr 2

Zrób gdzieś pusty div, powiedzmy, że dałem div div identyfikator „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>

Wystarczy, że prześlesz formularz, aby zadzwonić pod numerFunkcja JavaScript do porównania, jeśli chcesz przesłać formularz, jeśli dane są prawidłowe, możesz to zrobić za pomocą AJAX. Poprzedni plakat jest poprawny, ponieważ trudno jest na nie odpowiedzieć bez dodatkowych informacji na temat tego, co konkretnie próbujesz zrobić.


0 dla odpowiedzi № 3
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");
}


});

0 dla odpowiedzi nr 4

Jeśli odejmiesz 1 od długości, możesz zwrócić 0 bez duplikatów.

Przekażę także element i nazwę atrybutu, aby można było ponownie użyć.

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