在each()中访问div内的输入值 [英] Accessing value of inputs within a div in each()
问题描述
我有一些代码,允许用户将新手机添加到类似
I have a bit of code that allows a user to add a new phone to a list like so
const addPhone = async (phone) => {
$('.phone-list').append(`
<div class='phone-div'>
<table">
<tbody>
<tr>
<td">
<p>
<input class='type' type='text' value='${phone.type}'></input>
</p>
<p>
<input class='detail' type='text' value='${phone.detail}'></input>
</p>
</td>
</tr>
</tbody>
</table>
</div>);
};
每次用户添加新电话时,都会将新的电话div添加到列表中并显示在屏幕上.
Each time a user adds a new phone a new phone-div is added tothe list and turns up on screen.
现在,当用户点击提交按钮时,我想从每个phone-div中读取数据,创建一个对象,然后将该obj推入一个数组,然后可以将其作为JSON发送给我的API进行处理...目前,我正在尝试使用此
Now when the user taps a submit button I want to read the data from each phone-div create an object with and push that obj into an array that I can then send as JSON to my API to process... currently I am trying to use this
$(document)
.on('click', '#submit', async () => {
const phoneArray = [];
$('.phone-div').each((i) => {
console.log($(this).find('.type'));// returns undefined
console.log($(this).find('.detail'));// returns undefined
});
});
如何获取类型和详细信息到obj中,然后将其推入数组,然后可以像
How can I get this to put type and detail in an obj and then push it into an array that I can then send to the server like
phoneArray.push({
type: $(this).find('.type').val(),
detail: $(this).find('.detail').val(),
})
推荐答案
I don't know what you expected using async
. A "normal" function perfectly does the job.
在.append()
...
function addPhone(phone){
$('.phone-list').append(`
<div class='phone-div'>
<table>
<tbody>
<tr>
<td>
<p>
<input class='type' type='text' value='${phone.type}'></input>
</p>
<p>
<input class='detail' type='text' value='${phone.detail}'></input>
</p>
</td>
</tr>
</tbody>
</table>
</div>
`);
}
$(document).on('click', '#submit', function(){
const phoneArray = [];
$('.phone-div').each(function(i){
console.log($(this).find('.type').val());
console.log($(this).find('.detail').val());
phoneArray.push({
type: $(this).find('.type').val(),
detail: $(this).find('.detail').val(),
})
});
console.log(phoneArray);
});
$("#add").on("click",function(){
// just for the demo... Since I can't know where this object comes from...
var phone = {type:"cellular",detail:"1-888-555-5555"}
addPhone(phone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="phone-list"></div>
<button id="add">Add</button>
<button id="submit">Submit</button>
这篇关于在each()中访问div内的输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!