gpt4 book ai didi

javascript - Jquery:根据相同的输入名称检查重复的值

转载 作者:行者123 更新时间:2023-12-02 15:51:29 24 4
gpt4 key购买 nike

我有多个隐藏输入,如下所示:

<input type="hidden" value="4531" name="product_id">
<input type="hidden" value="4532" name="product_id">
<input type="hidden" value="4533" name="product_id">

我如何检查它的值在表单提交时是否重复,我的jquery代码如下(不起作用):

$(".btnSubmit").click(function() {
var errorCounterDupInput = 0;
$("input[name='product_id']").each(function (i,el1) {
var current_val = $(el1).val();
console.log("current_val : "+current_val);
if (current_val != "") {
$("input[name='product_id']").each(function (i,el2) {
if ($(el2).val() == current_val && $(el1).attr("name") != $(el2).attr("name")) {
errorCounterDupInput = errorCounterDupInput+1;
}
});
}
});
});

即使我有这样的重复项,errorCounterDupInput 的输出也始终为 0:

<input type="hidden" value="4531" name="product_id">
<input type="hidden" value="4531" name="product_id">
<input type="hidden" value="4531" name="product_id">

有什么想法吗?

最佳答案

这里有两个问题。

  1. 您要求名称属性不同才能重复,($(el1).attr("name") != $(el2).attr("name")) 并且您已经确保它们与您的 jQuery 选择器相同。所以不会出现重复的情况。
  2. 您将每个元素与所有元素进行比较,包括每个循环本身,因此即使您修复了名称错误,您也会得到比实际更多的重复项。

我建议在循环元素时,缓存它们的值,并且仅将新值与现有缓存进行比较,这样您就能准确了解重复计数。

$(".btnSubmit").click(function () {
var errorCounterDupInput = 0;
var product_ids = [];
$("input[name='product_id']").each(function (i, el1) {
var current_val = $(el1).val();
console.log("current_val : " + current_val);
if (current_val != "") {
if(product_ids.indexOf(current_val) === -1){
product_ids.push(current_val);
} else {
errorCounterDupInput++;
}
}
});
console.log(errorCounterDupInput);
});

fiddle : http://jsfiddle.net/trex005/Lnogg68v/

关于javascript - Jquery:根据相同的输入名称检查重复的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31822351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com