我有两个 HTML 选择框。我将选项从一个框移动到另一个框,分别为框“from[]”和框“to[]”。我遇到的问题是,“to[]”框在添加选项时按字母顺序对选项进行排序。我希望每个选项都附加到框中并且根本不排序。
我对此进行了大量阅读,似乎“to[]”框应该保持选项添加时的顺序,但事实并非如此。
我在 Javascript 中留下了注释掉的代码,这样您就可以看到我尝试过的内容。如果它让一切变得太困惑,我会将其删除。
谢谢!
HTML:
<select name="from[]" id="fabricBox" class="form-control" size="8" multiple="multiple" style="width:100%">
<select name="to[]" id="fabricBox_to" class="form-control" size="8" multiple="multiple" required></select>
Javascript:
$('#fabricBox').dblclick (function(){
$value = $('#fabricBox option:selected').val();
$('#fabricBox_to').append($value);
// $('#fabricBox_to').val() = $value
// $text = $('#fabricBox option:selected').text();
// $("#fabricBox_to").append($('<option></option>').attr("value",$value).text($text));
最佳答案
您可以通过四个步骤来完成此操作:
1) 您可以映射所有选定选项并将它们作为分隔字符串返回(,)
2) 现在将字符串分割为数组。
3) 删除从从选择元素移动到到选择元素的项目。
4) 最后循环遍历数组,将选项附加到第二个选择元素。
<小时/>下面的多选示例
//move items from fabricBox to fabricBox_to
$("#move").on("click", function(){
MoveToandFrom("#fabricBox", "#fabricBox_to");
});
//You can even move the options back if you need to
$("#moveBack").on("click", function(){
MoveToandFrom("#fabricBox_to", "#fabricBox");
});
//reusable function that moves selected indexes back and forth
function MoveToandFrom(fromSelectElement, toSelectElement)
{
//get list of selected options as delimited string
var selected = $(fromSelectElement + " option:selected").map(function(){ return this.value }).get().join(", ");
//if no option is selected in either select box
if( $.contains(selected, "") ){
alert("You have to select an option!");
return false;
}
//split the selected options into an array
var stringArray = selected.split(',');
//remove selected items from selected select box to second select box
$(fromSelectElement + " option:selected").remove();
//loop through array and append the selected items to Fabric_to select box
$.each( stringArray, function( key, value ) {
$(toSelectElement).append("<option>" + value + "</option>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label for="fabricBox">From</label>
<select name="from[]" id="fabricBox" class="form-control" size="8" multiple="multiple" style="width:100%">
<option>Fabric 1</option>
<option>Fabric 2</option>
<option>Fabric 3</option>
<option>Fabric 4</option>
<option>Fabric 5</option>
<option>Fabric 6</option>
</select>
<button id="move">Move Selected</button>
</div>
<br/>
<div>
<label for="fabricBox_to">To</label>
<select name="to[]" id="fabricBox_to" class="form-control" size="8" multiple="multiple" style="width:100%" required>
</select>
<button id="moveBack">Move Selected back</button>
</div>
关于javascript - 停止对选择框中的 HTML 选项进行自动排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810141/