我有两个HTML选择框。我正在将选项从一个盒子移动到另一个盒子,#34;从[]"和框#34;分别为[]。我遇到的问题是,"到[]"框在添加时按字母顺序对我的选项进行排序。我希望每个选项都附加到框中,根本没有排序。
我已经对此做了很多阅读,看起来好像是#34;对于[]"在添加选项时,框应保留选项的顺序,但不会。
我在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));
答案 0 :(得分:0)
我无法测试它,但这样的事情应该有效:
$("#fabricBox_to option:last").append('<option>' + $value + '</option>');
答案 1 :(得分:0)
您可以分四步完成:
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>