jQuery-从html数组输入获取值 [英] JQuery - Get values from html array inputs

查看:66
本文介绍了jQuery-从html数组输入获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户可以通过html输入添加尽可能多的项目.输入看起来像;

A user has the capacity to add as many items as possible through html inputs. The inputs look like;

 <input class="form-control" name="part_number[]" number" type="text">
 <input class="form-control" name="part_number[]" number" type="text">
 <input class="form-control" name="part_number[]" number" type="text">

 <input class="form-control item" name="description[]" type="text">
 <input class="form-control item" name="description[]" type="text">
 <input class="form-control item" name="description[]" type="text">

我想将项目添加到我的数据库中进行存储..我如何遍历每个输入?零件编号和描述属于同一行.

I would like to add the items to my database for storage.. How do i iternate through each input? part number and description belong to a single row.

推荐答案

从您的问题开始,我了解到您需要连续输入描述和部件号. 请使用jQuery的 .each 函数找到我的答案.

.each()函数遍历所有指定的元素,并返回每个元素的索引位置.在这里,我要遍历零件号,因此我想采用相应的描述,即在part_number的索引位置处的描述.要实现此目的,请使用另一个jQuery选择器:eq().它将选择匹配集中索引n处的元素.

From your question, I understand that you want the description and part number in a row. Please find my answer using .each function of jQuery.

The .each() function iterates through all the specified elements and it returns the index position of each element. Here I'm iterating through the part number, so I want to take the corresponding description, that is the description at the index position of part_number. To achieve this am using another jQuery selector :eq(). It will select the element at index n within the matched set.

$(".submit").on("click", function(){
let user_input = [];
$("input[name='part_number[]']").each(function(index){
 user_input.push({
 part_number: $(this).val(),
 description: $(`.item:eq(${index})`).val()
 });
});
console.log("final result = ", user_input);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" name="part_number[]"  placeholder="number" type="text">
 <input class="form-control" name="part_number[]" placeholder="number" type="text">
 <input class="form-control" name="part_number[]" placeholder="number" type="text">

 <input class="form-control item" name="description[]" placeholder="description" type="text">
 <input class="form-control item" name="description[]" placeholder="description" type="text">
 <input class="form-control item" name="description[]" placeholder="description" type="text">
 
 <button type="submit" class="submit"> Save</button>

这篇关于jQuery-从html数组输入获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆