gpt4 book ai didi

javascript - 将数组从表行传递到 JavaScript

转载 作者:行者123 更新时间:2023-11-28 19:19:29 24 4
gpt4 key购买 nike

我使用 JavaScript 函数将行动态追加到表中。

添加行函数:

function addrow(tableid) {
var tablename = document.getElementById(tableid);
var rows = tablename.rows.length;
if (rows < 8) { //Maximum number of rows allowed
var newrow = tablename.insertRow(rows);
var col = tablename.rows[0].cells.length;
for (var i=0; i<col; i++) {
var newcell = newrow.insertCell(i);
newcell.innerHTML = tablename.rows[0].cells[i].innerHTML;
}
}
else {
alert(" Maximum number of rows allowed is 8");
}
}

HTML 代码(行结构):

<tr>
<p>
<td width="20%">
<input class="input-group-lg" type="text" name="c_degree[]" style="width:90%"/>
</td>
<td width="25%">
<input class="input-group-lg" type="text" name="c_specialization[]" style="width:90%" />
</td>
<td width="30%">
<input class="input-group-lg" type="text" name="c_university[]" style="width:90%" />
</td>
<td width="15%">
<input class="input-group-lg" type="number" name="c_year[]" min="1990" max="2015" />
</td>
<td width="10%">
<input class="input-group-lg" type="number" name="c_marks[]" min="1" max="100" />
</td>
</p>
</tr>

我需要将数据(这些数组)从所有动态创建的行传递到 ajax 脚本(将其传递到后端)。

最佳答案

虽然使用 jQuery 可以轻松地从带有 $.serialize() 的表单中获取数据。 ,你必须在没有图书馆的情况下完成一些工作。让我们创建自己的 serialize() 函数,我们可以像这样使用它:

var myFormData = serialize( "myForm" ); // returns an object

请注意,“myForm” 可以替换为任何容器,甚至是 “myTable”

这是一个尝试:

function serialize(formID) {
// New object you'll be building upon
var obj = {},
// Other variables we're going to use
i,l,n,isArray,isNum,val;
// Your form's inputs
var inputs = document.getElementById(formID).getElementsByTagName('input');
// For each of them
for (i = 0, l = inputs.length; i < l; i++) {
// Get their name
n = inputs[i].getAttribute('name');
// Is it an array?
isArray = n.slice(-2) == '[]';
// Is is of type "number"?
isNum = inputs[i].getAttribute('type') == 'number';
// What's the value?
val = inputs[i].value;
// If it's an array
if (isArray) {
// Get rid of the "[]"
n = n.substring(0, n.length - 2);
// If it's the first entry, create an empty array
if (obj[n] === undefined) obj[n] = [];
// Push the value in it (parsed as an integer if it's a number)
obj[n].push(isNum ? +val : val);
// If it's a single field, just assign it
} else obj[n] = isNum ? +val : val;
}
// Return the object
return obj;
}

JS Fiddle Demo (with random data)

请注意,此函数将与您提供的输入(“文本”和“数字”)一起使用,但需要完成才能与其他类型的输入一起使用,例如单选按钮、选择下拉列表、文本区域等。需要额外的工作,但如果您不想重新发明轮子,您可能会在网络上找到一个完全可用的工具。

关于javascript - 将数组从表行传递到 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29135132/

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