我正在尝试从HTML表中的选择框中检索值.如何选择所选值?
到目前为止,我已经尝试过:
this.cells[14].innerHTML;
this.cells[14].children[0].innerhtml;
this.cells[14].children[0].innerText;
The last one .innerText returns all the items in my select Box......
var table2 = document.getElementById('table_items_program');
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function () {
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("select").value = this.cells[14].children[0].innerText;
}
}
<td><select class="selectpicker" multiple>
<?PHP while ($row9 = MysqLi_fetch_assoc($result9)):; ?>
<option value="<?PHP echo $row9['id']; ?>"><?PHP echo $row9['id'];?>
</option>
<?PHP endwhile; ?>
</select></td>
<input style="display: inline" id="id" name="id">
<input style="display: inline" id="select" name="select">
从HTML表中的选择框中选择的值
最佳答案
How can I select the selected value?
您可以使用HTMLSelectElement.selectedIndex
方法获得选定的索引
但是,如果我了解您的麻烦.您尝试获取所选的当前值.因此,您需要获取所选选项的值.
您可以这样做:
document.getElementById('mySelect').onchange = function() {
let options = this && this.options;
let selectedValues = []
for (var i = options.length; i--;) {
let opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
console.log(selectedValues)
}
<select id="mySelect" multiple>
<option value="a"> a </option>
<option value="b"> b </option>
<option value="c"> c </option>
</select>
实施到您的代码示例中
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function() {
document.getElementById("id").value = this.cells[0].innerHTML;
var options = this && this.cells[14].children[0].options;
var selectedValues = []
for (var i = options.length; i--;) {
var opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
document.getElementById("select").value = JSON.stringify(selectedValues);
}
}