2015-09-24 16 views
5

選擇我有一個多項選擇的形式,看起來像這樣:只有一個選項可以用HTML多選形式

<select multiple="multiple" id="id_form-0-project" name="form-0-project"> 
    <option value="0">and another test</option> 
    <option value="1">another test</option> 
    <option value="2" selected="selected">one more test</option> 
    <option value="3">test project</option> 
</select> 

人們可以看到,有一個選擇的值。這總是我選擇的第一個選項。但是,當我通過Shift點擊或命令點擊選擇多個選項時,新選擇的項目不會被調整以包含selected =「selected」屬性,即使在視覺上,對於用戶來說顯示所述選擇被突出顯示。

在這方面,要表現得像一個單一的選擇,但我想,加入了「多個=」多」屬性將允許指定所選屬性的多個選項。

這是一個常見的問題?莫非它必須是與刷新頁面?什麼是預期的行爲?

回答

7

...新選擇的項目,不進行調整,以便包含選定=「選擇」屬性...

Ri GHT。您還會注意到,input上的value屬性在用戶更新其值時未更新(例如,如果您查看outerHTML)。

這就是事情的工作原理。這不是一個錯誤或你做錯了什麼。控件的運行時狀態不會反映在元素的HTML屬性模型中。

預期的行爲是什麼?

這是預期的行爲。如果您想知道選擇了哪些項目,請不要查找屬性,查看選項的屬性(非屬性)的selected

如果你想選擇HTMLOptionElement實例的數組:

var selected = Array.prototype.filter.call($("id_form-0-project")[0].options, function(option) { 
    return option.selected; 
}); 

如果你想實際值,與.map結合起來:

var selected = Array.prototype.filter.call($("#id_form-0-project")[0].options, function(option) { 
    return option.selected; 
}).map(function(option) { 
    return option.value; 
}); 

你當然可以,很容易將其包裝到自己最小的jQuery插件中:

jQuery.fn.selectedValues = function() { 
    if (!this[0] || !this[0].options) { 
     return undefined; 
    } 
    return Array.prototype.filter.call(this[0].options, function(option) { 
     return option.selected; 
    }).map(function(option) { 
     return option.value; 
    }); 
}; 

然後

​​

你(好)問題突出的DOM和HTML序列化和瀏覽器是如何經過多年的發展中(很多)黑暗的角落之一。沒有人會有這個設計這個。 :-)然而,怪癖和所有,它的效果令人驚訝。

+0

好的,謝謝你這很高興知道。我最終試圖獲得所有選定項目的列表,以便我可以相同地選擇具有相同選項的其他表單。在我使用$(「#id_form-0-project」).find(「:selected」)。之前val()|| []方法,但看起來我將不得不嘗試其他的東西。 – Malonge

+0

@Malonge:完全合理的方法,它不起作用。 :-)我已經爲如何做到這一點的答案添加了幾個想法。 –

1

既然你標記爲jQuery

雖然沒有更新的HTML標籤本身的屬性,在selected屬性的值更新爲與用戶界面保持一致。

你仍然可以準確地確定選擇哪些項目使用$(element).prop('selected')作爲例子:

http://jsfiddle.net/17s4q7ht/

HTML:

<select multiple="multiple" id="id_form-0-project" name="form-0-project"> 
    <option value="0">and another test</option> 
    <option value="1">another test</option> 
    <option value="2" selected="selected">one more test</option> 
    <option value="3">test project</option> 
</select> 
<div id="status"></div> 

JS:

$('#id_form-0-project').on('change', function() { 
    $('#status').text($(this).find('option').map(function(i, e){ 
     return $(e).val() + " is " + ($(e).prop('selected') ? "" : "not ") + "selected"; 
    }).get().join('; ')); 
}); 
+0

您瞭解我的想法。出於這個原因,我確實包含了jQuery標籤。我需要找出哪些選項被選中,所以我可以做出相同的選擇另一種形式。我認爲這將有助於做到這一點。 – Malonge

相關問題