gpt4 book ai didi

Jquery,将输入数据传递到数组

转载 作者:行者123 更新时间:2023-12-01 08:33:06 25 4
gpt4 key购买 nike

我在文本字段上有一组数组

<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">

如何防止传递重复数组

这是我的 jquery 代码

  $(document).on("click", ".open_modal", function() {

//var values = $('input[name^="owner"]').map((i, a) => a.value).get();
var values = $('input[name="owner[]"]').val();


if(values == values) {
alert('exist'); /* how to validate duplicate array */
}
$("#owner_value").val(values);

});

最佳答案

我们可以使用Array.filter()来过滤重复值,values.filter((a, b) =>values.indexOf(a) === b);

在此之前,我们需要将所有值推送到一个数组中。这就是我所做的

var values = [];
$('input[name="owner[]"]').each(function() {
values.push($(this).val());
});

var $ = jQuery;
$(document).on("click", ".open_modal", function() {
var values = [];
var owners = ['john', 'wons', 'kolins'];
$('input[name="owner[]"]').each(function() {
values.push($(this).val());
});
values = [...values, ...owners]; // here we merge both arrays and then remove the duplicates.
if(values.length) {
values = values.filter((a, b) => values.indexOf(a) === b);
// console.log(values); // now duplicates are removed.
}
var htmlContent='';
values.forEach((user)=>{
if(user){
htmlContent +=`<p>${user}</p></br>`;
}
})

$("#owner_value").html(htmlContent);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Reys">
<input type="text" name="owner[]" value="Jan">

<p> Test btn </p>
<button class="open_modal">Open Modal </button>

<div id="owner_value"></div>

关于Jquery,将输入数据传递到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59979085/

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