2017-06-05 226 views
1

在一個表單中我有兩個多選。我可以選擇1項添加到選擇2或使用下面的jQuery函數刪除選擇2項:多選擇添加/刪除在jquery中選擇

<script type="text/javascript"> 
    function addProject() {  
     return !$('#select1 option:selected').remove().appendTo('#select2'); 
    } 

    function removeProject() { 
     return !$('#select2 option:selected').remove().appendTo('#select1'); 
    } 
</script> 

<select multiple id="select1" class="form-control"> 
@for(p <- projects) { 
    option value="@p.getName">@p.getName</option> 
} 
</select> 

<button type="button" class="btn btn-primary" onclick="addProject();" > 
    <span class='glyphicon glyphicon-plus'></span> 
</button> 
<button type="button" class="btn btn-primary" onclick="removeProject();" > 
    <span class='glyphicon glyphicon-minus'></span> 
</button> 

<select name="projects" multiple id="select2" class="form-control"> 
</select> 

的問題是,如果我將項目添加到選擇2和提交表單我收到的所有值。如果我添加和刪除項目,反之亦然,我沒有收到價值。

我試圖添加另一個jquery函數來選擇提交表單之前select2中的所有項目,但沒有工作。

function select_projects() { 
    $('#select2').children('option').attr('selected', 'selected'); 
} 

如何解決問題?

+0

試試這個:https://stackoverflow.com/questions/13268083/select2-changing-items-dynamically – Zenoo

+0

我檢查,但不似乎與我的問題有關。 –

+0

就像在這個答案中所說的,當你想要選擇你的選項時,你需要再次調用'.select2()'函數。 – Zenoo

回答

1

我解決了改變select_projects()函數類似如下:

function select_projects() { 
    $('#select1 option:selected').attr('selected', false); 
    $('#select2').children().prop('selected', true); 
} 
相關問題