我有一个包含表格和小表格的页面。该表有一些问卷调查数据。我试图使用jquery
遍历表,检查是否满足条件,然后将其添加到表单的正确字段。我遇到的问题是表单不是由我创建的,所以我不能匹配它们来设置id's
。所以我需要从field_id
获取relate
,并将answer
插入location
。我是Jquery和js的新手。这就是我想出来的。
HTML
<div align="left">
<table class="table table-striped">
<thead>
<td>Question</td>
<td>Answer</td>
<td>Relates to</td>
</thead>
<tbody>
<tr>
<td>Random question 1</td>
<td>Random answer 1</td>
<td>add to variable form field</td>
</tr>
<tr>
<td>Random question 2</td>
<td>Random answer 2</td>
<td>add to a different form field</td>
</tr>
</tbody>
</table>
</div>
<input type="text" id="variable id that could be matched with element of table">
main.js
table.find('tr').each(function (i, el) {
var $mylists = $('#' + relate)
$mylists.html('');
var $tds = $(this).find('td'),
label = $tds.eq(0).text(),
relate = $tds.eq(1).text(),
answer = $tds.eq(2).text();
$('<span></span>').text(answer).appendTo($mylists);
});
答案 0 :(得分:0)
由于您要为您添加值的单个输入,因此需要设置输入的val
。并且由于您想要从多个其他值(答案)创建单个输入值,您需要循环,获取所有答案,然后将它们组合成单个值。像这样:
var $mylists = $('#' + relate);
$mylists.val('');
var answers = [];
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
label = $tds.eq(0).text(),
relate = $tds.eq(1).text(),
answer = $tds.eq(2).text();
answers.push(answer);
});
// at this point, answers contains an array of all your individual answer values.
// decision time: what do you want to do with them?
// in this example, I join them together in a comma-delimited list.
$mylists.val( answers.join(', ') );