我通过json接收一些数据并根据输入动态创建了一个表格,该表格根据输入中的值显示预先选择的单选按钮(绿色/黄色/红色)。在第三列中,我显示了一个注释框。
现在,我只想在黄色/红色单选按钮作为输入或我选择时显示评论框。
以下是我正在使用的代码:
$(document).ready(function() {
var appStatus = [{
"category": "Overall Status",
"status": "0"
}, {
"category": "System Availability",
"status": "1"
}, {
"category": "Whatever",
"status": "2"
}];
var tr;
for (var i = 0; i < appStatus.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + appStatus[i].category + "</td>");
tr.append('<tr id="row' + i + '"><td><input type="radio" name="inlineRadioOptions_' + i + '[]" value="0" id="inlineRadio0"' +
(appStatus[i].status == '0' ? ' checked="checked"' : '') +
'><font color="black">Grey  </font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" value="1" id="inlineRadio1"' +
(appStatus[i].status == '1' ? ' checked="checked"' : '') +
'><font color="green">Green  </font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio2" value="2"' +
(appStatus[i].status == '2' ? ' checked="checked"' : '') +
'><font color="yellow">Yellow  </font></label><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio3" value="3"' +
(appStatus[i].status == '3' ? ' checked="checked"' : '') + '> <font color="red">Red</font></label><td></tr>');
//tr.append("<td>" + "<input>" + appStatus[i].comments + "</input>" + "</td>");
tr.append("<td>" + '<tr id="row' + i + '"><td><input type="text" id="appStatus[i].comments" name="appStatus[i].comments" placeholder="Comments" class="form-control name_list" required' + "</td>");
$('table').append(tr); }
$('#result').on('click', function() {
var new_status = [];
$('.table tbody tr').each(function() {
new_status.push({
category: $(this).find('td:eq(0)').text(),
status: $(this).find(':radio:checked').val()
});
});
console.log(new_status);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover">
<thead>
<th>Category</th>
<th>Status</th>
<th>Comments</th>
</thead>
</table>
答案 0 :(得分:0)
为每个无线电输入添加处理程序。由于您使用的是jQuery,因此附加的事件处理程序将this
作为事件源。您必须将较长的<tr>...</tr>
块分开才能实现此目的。
一个简单的例子:
table.append('<tr/>').append(
$('<td>').append(
$('<input type="radio" name="x">').change(function () {
$(this).closest('td').find('input.comments').toggle(true or false);
})
)
)
...但你可以更聪明,并使用变量更清楚地写出来。
您还要在代码中将<tr>
元素添加到另一个元素中,这会导致HTML无效。还有一些需要处理的小故障。