2011-10-09 39 views
1

請你能幫助我,我知道它是一個非常新的問題,但我從來沒有真正使用過這個,並且努力在谷歌中找到相關的結果。通過<select>/<option>列出並通過PHP和Javascript收集值?

基本上我有一個<select>內一套<option>並希望使用JavaScript來刪除已選擇的所有值,把它們放入一個字符串,然後將其張貼到我的PHP腳本...

任何想法?

非常感謝您提前。

灰。

+0

這是什麼意思「我裏面有一組的」?請澄清。 –

回答

1

只使用的JavaScript/DOM 我猜select有多個屬性

var selectElem = document.getElementById('myselect'); // your select element 
var strSelection = ''; // string to store the selected stuff 
for(let count = 0, limit = selectElem.options.length; count < limit; count++) //check every option 
    if(selectElem.options[count].selected) // check if it's selected 
     strSelection += selectElem.options[count].value + ','; // Concat to string and add delimiter, string format is up to you, here i add the .value but could also be .text or both.. 
selectElem.selectedIndex = -1; //Resets the selection element so all options are unselected 
2

我寫了一個使用jQuery的example,因爲它使得解決方案非常簡單。

var str = ""; 
// iterates over all selected options and generates the value-string. 
$('#id option:selected').each(function(k,el) { 
    str += $(el).val()+', '; 
}); 

// removes all selected options 
$('#id option:selected').remove(); 

將數據發送到服務器看看這jQuery函數:jQuery.get()jQuery.post()