鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ multipleselect用在form提交頁面中如何獲取選中的值?

multipleselect用在form提交頁面中如何獲取選中的值?

問題描述

form表單中有multipleselect控件,但是獲取不了值?

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

直接在js中操控

相關(guān)代碼

// 請(qǐng)把代碼文本粘貼到下方(請(qǐng)勿用圖片代替代碼)
$('#multiselect').change(function(){

         $('select :selected').each(function() {
            str +=','+$(this).val();
         });
         //把str作為form中action的參數(shù)
});

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

回答
編輯回答
安于心

http://api.jquery.com/val/ 官方文檔中有如下描述信息

When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null.

因此下面的代碼可以拿到選中的值

<select id="elem" multiple="multiple">
    <option>...</option>
    ...
</select>
var values = $('#elem').val();
2017年5月1日 13:17