首页 > 解决方案 > 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.

标签: jquery

解决方案


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>&nbsp;</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>


推荐阅读