jquery - Insert value to table at a specific index using jquery
问题描述
I am facing some challenges with a code I am working on. I have multiple select tags (eg color, size etc) from which you can make selections. Each value selected from the different select tags is inserted in a td tag in a table. The select tags can be assessed at random so from header as below
SN | Color | Size | Quantity |
---|
When you select size "3" from the "Size" drop down, the table should be populated as below
SN | Color | Size | Quantity |
---|---|---|---|
1. | 3 |
The problem I have is that even though the headers are fixed, I cannot seem to be able to insert/update that single td to be as above expected result.
What I have tried:
var size = $(this).find('option:selected').text();
//Works fine
$('table tbody tr td').eq(1).after('<td>'+size+'</td>');
The above inserts the value but shifts everything to the right and that row ends up being more than the number of headers. (Not what I want)
I have also tried other thing which I know are incorrect.
Also, if someone could help with a way to make sure I am updating the particular row. What I did was to subtract 1 from SN ie (sn-1). Hope my question is clear about my intent here.
解决方案
You can use a data-
attribute on each select to identify the column index like:
<select data-col="1">
Simple example:
// just to add some option values
initDemo();
$('select').change(function(){
const tableCol = $(this).data('col'),
text = $(this).find(':selected').text()
$('tbody td').eq(tableCol).text(text);
});
function initDemo() {
const data = [
['Green', 'Red', 'Blue'],
['Large', 'Medium', 'Small'],
[1, 4, 10]
];
data.forEach((arr, i) => $('select').eq(i).append(arr.map(v => new Option(v, v))))
}
td{width:60px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Color :
<select data-col="1">
<option value=""></option>
</select>
Size :
<select data-col="2">
<option value=""></option>
</select>
Qty :
<select data-col="3">
<option value=""></option>
</select>
<hr/>
<table border=1>
<thead>
<tr>
<th>SN</th>
<th>Color</th>
<th>Size</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
推荐阅读
- angular - 子组件输入变量的setter/ngOnChanges方法只调用一次?
- neo4j - 从neo4j中的json文件导入和创建多个标签和关系
- laravel - PHPOffice 电子表格到 PDF 导出
- react-native - 如何将两个类指定给像“View”或任何其他的 react-native 组件?
- spring-boot - javax.servlet.ServletContext 类型无法解析。它是从所需的 .class 文件中间接引用的
- java - 从 Wildfly 系统 (standalone.xml) 读取配置参数
- javascript - Firebase .where('smth','==',true) 查询无法正常工作
- xcode5 - 缺少一些 Xcode 构建设置
- python - 在运行时在属性文件中的换行符上写入数据?
- python - 为什么anaconda navigator 1.9.6 打开真的很慢?