Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

javascript - How can I move selected option in multiselect up and down by buttons using jquery?

I have select

<select multiple id="select2"> 
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option>
</select>

And two buttons

<input type="button" value="Up" onclick="up()">
<input type="button" value="Down" onclick="down()">

How can I move selected option in multiselect up and down by buttons using jquery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update: Fixed code for multiple options selected, based on @patrick dw's suggestion.

$(document).ready(function(){
    $('input[type="button"]').click(function(){
        var $op = $('#select2 option:selected'),
            $this = $(this);
        if($op.length){
            ($this.val() == 'Up') ? 
                $op.first().prev().before($op) : 
                $op.last().next().after($op);
        }
    });
});

Test it here »

No need to use inline onclick="" event listeners. jQuery takes full control of separating presentation from functionality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...