开发者

How to get previuos item of Dropdown using jquery or javascript

I want to get the previously selected value of a dropdown control using jquery or javascript. How can i get this? I tried with prev() selector of jquery but failed

$(ddlStatus).find("option").prev(":selected").attr("text");

if ddlStatus has items like A,B,C,D,E When the page loads B is sele开发者_如何学JAVActed but when user changes the item {let's say) E then I want previously selected i.e B.


Whenever a selection is made, save the value. On a new selection, you will then have the old value saved until you overwrite it.

You cannot do this dorectly, as you are after historical information - prev is about the ordering not the timing.


You could do it like this (not optimized but works):

$(document).ready(function(){
   $(ddl).data('lastSelected', $(ddl).val());
});
$(ddlstatus).change(function(){
   var lastSelected = $(this).data('lastSelected');
   $(this).data('prevLastSelected', lastSelected);
   $(this).data('lastSelected', $(this).val());
});

Then, to know the previously selected anytime, you just do:

var previouslySelectedValue = $(ddl).data('prevLastSelected');

What's good about this code is that the state is saved in the element and you don't use global vars, so it can be applied to any number of select boxes

Hope this helps. Cheers


here is a example:

HTML:

<select id="myselect">
  <option value="one" selected="selected">one</option>
  <option value="two">two</option>
  <option value="three">three</option>
</select>

JQUERY:

var prev = null; //global
var cur = $('#myselect').val();//global
var flag = true;// global

$('#myselect').change(function() {
    if (flag) {
        prev = cur;
        cur = $(this).val();
        flag = false;
    } else {
        prev = cur;
        cur = $(this).val();
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜