簡體   English   中英

將下拉列表中的多選值添加到數組

[英]Add multi select values from drop down list to an Array

我試圖從多選下拉列表中獲取選定的值,並將選定的值添加到數組中。

我目前使用的方式是,它在下拉列表中添加所有值,而不是所選值。

這是HTML:

<div class="form-group">
    <select multiple class="form-control" id="servicePackageTypeText">
        <option disabled selected value> -- select an option -- </option>
        <option><?php echo $servicehtml ?></option>
    </select>
</div>

這是JavaScript:

var sourcetype = document.getElementById("servicePackageTypeText"); 
var servicearray = new Array();

for (i = 0; i < sourcetype.length; i++) 
{ 
    servicearray.push(sourcetype.options[i].value);
}

關於如何獲取所選值的任何提示? 謝謝。

我可以在for循環中使用“ selectOptions”解決此問題:

var sourcetype = document.getElementById("servicePackageTypeText"); 
var servicearray = new Array();
for (i = 0; i < sourcetype.selectedOptions.length; i++) 
{ 
    servicearray.push(sourcetype.selectedOptions[i].value);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM