简体   繁体   中英

Move selected items to the top of sorted multiple select (Javascript)

I'm using jQueryUI multi-select Widget that draws a nice dropdown menu widget for multi-selects.

I have an already sorted (on username) multiselect like that:

<select multiple="multiple" name="users" id="id_users">
<option value="1" selected="selected">aaa</option>
<option value="44">bbb</option>
<option value="21" selected="selected">ccc</option>
<option value="50">ddd</option>
<option value="16">eee</option>
<option value="25" selected="selected">fff</option>
</select>

And I want to keep the username sorting, but moving the selected items to the top of the list, everytime the user opens the drop down menu. So in this example the new order must be:

<select multiple="multiple" name="users" id="id_users">
<option value="1" selected="selected">aaa</option>
<option value="21" selected="selected">ccc</option>
<option value="25" selected="selected">fff</option>
<option value="44">bbb</option>
<option value="50">ddd</option>
<option value="16">eee</option>
</select>

From the website of the widget, I see that it has a method that returns an array of selected items, and it has an event beforeopen. So I think I can manage the sorting (using that array) by handling the event beforeopen, but I'm rather new to javascript, anyone can point me in the right direction please?

I searched here, and all the solution I found solve the problem "sort on text" (which is not what I need).

EDIT: I solved in this way:

$('#id_users').multiselect({
    beforeopen: function(event, ui) {
        $('#id_users option:selected').prependTo('#id_users');
        $('#id_users').multiselect('refresh');
    }
});

So in initialization of the widget, I bind those two lines of code to the beforeopen event. In the handling of beforeopen I prepend the selected items to the others, and refresh the widget (because it reads the multi-select only once, and if you don't refresh the order remains the same, even if the HTML changes).

I can't upvote the answer because I don't have enough reputation. But thanks!

Try this.

$('#id_users option:selected').prependTo('#id_users')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM