The code below mostly works. The problem is that if I remove an item from the right box and add into left box (or vice versa) then list does not sort alphabetically.
I tried with sort() function. For example, self.catagories.sort(), however it didn't work. It always adds the item at the end. I need help for this solution.
var categoryModel = function(category) {
this.category = ko.observable(category);
};
var viewModel=function(){
var self=this;
self.categories=ko.observableArray([new categoryModel("Hello"),new categoryModel("DHFDSHADS"),new categoryModel("yo"),new categoryModel("jai")]);
self.selectedCategory=ko.observableArray();
$('#add').click(function() {
var x= $('#select1 option:selected');
if(x.length>0){
x.each(function(){
alert($(this).text());
self.selectedCategory.push(new categoryModel($(this).text()));
$('#select1 option:selected').remove();
});
}
});
$('#remove').click(function() {
var x= $('#select2 option:selected');
if(x.length>0){
x.each(function(){
alert($(this).text());
self.categories.push(new categoryModel($(this).text()));
$('#select2 option:selected').remove();
});
}
});
};
$(document).ready(function() {
ko.applyBindings(new viewModel());
});
.liveExample select[multiple] { width: 20%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<div class='liveExample'>
<p>Your items:</p>
<select multiple="multiple" id ="select1" width="5" data-bind="options: categories,optionsText:'category'"> </select>
<span>
<a href="#" id="add"> >> </a>
<a href="#" id="remove"> << </a>
</span>
<select multiple="multiple" id ="select2" width="5" data-bind="options: selectedCategory,optionsText:'category'"> </select>
</div>