[英]How to retrieve the value of the selected option from a dynamically created select in a table
[英]How do you get the value of the selected option from a dynamically created select element?
我有一個按鈕來動態創建 select 元素,我是這樣創建的:
var units = units_array[0];
//ingredient unit of measurement drop down
var cell3= row.insertCell(2);
var unit_of_measure = document.createElement("select");
unit_of_measure.name = "unit_of_measure_select";
cell3.appendChild(unit_of_measure);
//Create and append the options
for (var i = 0; i < units.length; i++) {
var option = document.createElement("option");
option.value = units[i];
option.text = units[i];
unit_of_measure.appendChild(option);
}
但是,當我在 select 內部(在另一個函數的循環內)時,我在控制台中收到此錯誤:
未捕獲的類型錯誤:無法讀取未定義的屬性“未定義”
這是我用來訪問位於表格內的 select 元素的代碼。
var table = document.getElementById('selected_ingredients');
var rowCount = table.rows.length; //empty table has 2 rows (header + something else?)
var cellsCount = table.rows[0].cells.length -1 ; //table width in cells by counting headers minus the last cell (delete)
for (var r = 1; r < rowCount; r++) { //loop through all rows (r) in table
var $ingredient_dict = {}; //initiate dictionary for this ingredient
for (var c = 0; c < cellsCount; c++) { //loop through each cell (c) in row
var $cell = table.rows[r].cells[c];
if ($cell.innerHTML.includes("select")) { //if its is 3rd iteration (3rd cell along = select box)
alert("test");
//not working - undefined value from generated select element
var UOM = $cell.options[$cell.selectedIndex].value;
alert(UOM);
我想在 var UOM 中返回所選選項的值。 我對 js 比較陌生,所以如果這很簡單,我很抱歉。
在您的 if 語句中,您可以獲取 select 元素的句柄:
$select = $cell.querySelector('select');
//then to grab the option and value
var UOM = $select.selectedOptions[0].value;
alert(UOM);
我還建議在您的 if 語句中,而不是檢查 innerHTML 中的文本:
$cell.querySelector('select');
這將返回 null 如果不存在 select 元素,則等效於 false,但在存在元素時返回 true。 優點是,如果其中一個單元格包含單詞“select”,無論出於何種原因,如果您正在檢查字符串“select”,它將返回 true 並嘗試 select 不存在的元素,但是如果您正在尋找您剛剛找到它的元素。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.