How can I reorder a select list on the fly?
In my application, I have an HTML select box from which I remove and add items based on various user actions (the items become available/unavailable). However, I would also like all items to be displayed in preferred order, so every time I return an item to the select list, I n开发者_StackOverfloweed to re-sort in preferred order and select the preferred option. I've been unsuccessful thus far.
This is what I've got currently:
function update_select (select_id) {
// Rebuild given select box with appropriate options
var s = $(select_id);
s.empty();
for (index in order_by_kind(selectable)) {
var option = selectable[index];
var s_option = $('<option value="' + option.value + '">' + option.desc + '</option>')
s.append(s_option);
if (index == 0) {
s_option.attr('selected', true);
console.log(s_option);
}
}
}
If I log the results of order_by_kind()
, the option values are sorted as desired. I empty the contents of the list and rebuild it in the desired order, but the item always is last in the list. Logging s_option
shows that the option is set as selected, but the item is never selected in the UI. What might I doing wrong?
Edit:
My order_by_kind()
function is below, for those who would like to verify that it functions correctly:
function order_by_kind(obj_list) {
var tmp = [];
for (index in type_order) {
var kind = type_order[index];
for (obj_index in obj_list) {
var obj = obj_list[obj_index]
if (kind == obj.value) {
tmp.push(obj);
// break out of the inner loop
break;
}
}
}
return tmp
}
The problem was that although I was iterating over the ordered list, I was still referencing the unsorted list in order to build my options.
function update_select (select_id) {
// Rebuild given select box with appropriate options
var s = $(select_id);
s.empty();
// sort and write back the selectable items
selectable = order_by_kind(selectable);
for (index in selectable) {
var option = selectable[index];
var s_option = $('<option value="' + option.value + '">' + option.desc + '</option>')
s.append(s_option);
if (index == 0) {
s_option.attr('selected', true);
console.log(s_option);
}
}
}
Try this approach, storing and restoring the selected value:
function update_select (select_id) {
// Rebuild given select box with appropriate options
var s = $(select_id);
var val = s.val();
s.empty();
for (index in order_by_kind(selectable)) {
var option = selectable[index];
var s_option = $('<option value="' + option.value + '">' + option.desc + '</option>')
s.append(s_option);
}
s.val(val);
}
This may be a dead question, however its the first one in the search results - So i will post my solution here: The fiddle contains the compare functions for both value and html.
function reOrderOptions(select)
{
function compareOptions(optionA, optionB) {
return optionA.value - optionB.value;
}
var options = $(select + " option");
$(select).empty().append(options.sort(compareOptions));
}
Fiddle!
精彩评论