I have an multiselect option selector and up/down buttons:
<select id="animalSelector" multiple="multiple">
<option>Elephant</option>
<option>Duck</option>
<option>Dog</option>
<option>Giraffe</option>
<option>Dinosaur</option>
<option>Whale</option>
</select>
<input type="button" id="btnMoveUp" value="^ Up" />
<input type="button" id="btnMoveDown" value="v Down" />
I want the user to be able to highlight/select multiple options (using the CTRL key) and then be able to move their selections up and down.开发者_开发技巧
I've taken a stab at it:
$('#btnMoveUp').click(function (e) {
moveUp();
e.preventDefault();
});
$('#btnMoveDown').click(function (e) {
moveDown();
e.preventDefault();
});
function moveUp() {
var allOptions = $('#animalSelector').find('option');
allOptions.filter(':selected').each(function () {
var newPosition = allOptions.index(this) - 1;
if (newPosition > -1) {
allOptions.eq(newPosition).before(this);
}
});
}
function moveDown() {
var allOptions = $('#animalSelector').find('option');
var count = allOptions.length;
allOptions.filter(':selected').each(function () {
var newPosition = allOptions.index(this) + 1;
if (newPosition < count) {
allOptions.eq(newPosition).after(this);
}
});
}
However, this seems to act very slow/quirky in IE7 and it has some weird behavior when the selections start to reach the top.
Does anyone have any suggestions for the best way I can handle multiselect move-up/move-down behavior?
function moveUp() {
var select= $('#animalSelector')[0];
for (var i= 1, n= select.options.length; i<n; i++)
if (select.options[i].selected && !select.options[i-1].selected)
select.insertBefore(select.options[i], select.options[i-1]);
}
function moveDown() {
var select= $('#animalSelector')[0];
for (var i= select.options.length-1; i-->0;)
if (select.options[i].selected && !select.options[i+1].selected)
select.insertBefore(select.options[i+1], select.options[i]);
}
精彩评论