[基于使用JavaScript的下拉选择填充表中的多个字段,数据应位于数组中

问题描述 投票:-2回答:1

我想使用javascript根据下拉选择自动填充表格,并且输入必须来自数组。

javascript html dynamic dropdown populate
1个回答
0
投票

也许像这样:

     function chsnge_my_select(){
     	var select = document.getElementById('my_select');
        var cell1_text = select.options[select.selectedIndex].value;
        var cell2_text = select.options[select.selectedIndex].text;
        var data_arr = [cell1_text, cell2_text];
        add_to_my_tbl(data_arr);
     }
     function add_to_my_tbl(_arr){
     	if(!_arr[0] || !_arr[1]){
     		return false;
     	}
     	var table=document.getElementById('my_tbl');
        var row = document.createElement('tr');
        var cell1 = document.createElement('td');
        var cell2 = document.createElement('td');
        cell1.innerHTML = _arr[0];
        cell2.innerHTML = _arr[1];
        row.appendChild(cell1);
        row.appendChild(cell2);
        table.appendChild(row);
     }
     document.getElementById('my_select').addEventListener('change', chsnge_my_select, false);
<select id="my_select">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
  <option value="3">Item 3</option>
</select>
<table id="my_tbl" width="100%" border="1">
 <tr>
   <td>id</td>
   <td>name</td>
 </tr>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.