开发者

Efficient copy-down using jQuery

开发者 https://www.devze.com 2023-02-13 19:45 出处:网络
I have a piece of jQuery code that, when the user changes the value of a select, it copies the value selected down to other similar selects (same CSS class) that开发者_高级运维 follow the one changed,

I have a piece of jQuery code that, when the user changes the value of a select, it copies the value selected down to other similar selects (same CSS class) that开发者_高级运维 follow the one changed, if they don't have a value already. Is there a more efficient way to do the following? It runs a bit sluggishly, at least in IE7.

$('.selectclass').change(function() {
  if ($(this).val() != '') {
    var baseElem = $(this);
    $('.selectclass:gt(' + $('.selectclass').index(this) + ')').each(function (i) {
      if ($(this).val() == '') {
        $(this).val(baseElem.val());
     } 
    });
  }
}); 


This should be better optimised:

$('input.selectclass').change(function(){
    if (this.value !== '') {
        var newVal = this.value,
            boxes = $('input.selectclass');

        boxes.slice(boxes.index(this)).val(function(i, oldVal) {
            return oldVal === '' ? newVal : oldVal;
        });
    }
});

NB this is untested. If you could provide an HTML sample (e.g. jsfiddle) it could be tested more easily...

The efficiencies made here:

  • using input.selectclass should be faster than .selectclass, particularly in Internet Explorer
  • caching the selector rather than re-using it
  • using this.value rather than creating a new jQuery instance
  • using the inbuilt callback signature of val rather than doing the looping manually with each.


Because they are all the same class, do you need a foreach?

$('.selectclass').change(function() {
$('.selectclass').val($(this).val())
}


$('.selectclass').change(function() {
  if ($(this).val() != '') {
    $('.selectclass:gt(' + $('.selectclass').index(this) + ')').not(':empty').val($(this).val())
  }
}); 


You can use nextAll() to match the next sibling <select> elements down the tree:

$(".selectclass").change(function() {
    var origin = $(this);
    var value = origin.val();
    if (value !== "") {
        origin.nextAll(".selectclass").each(function() {
            var $this = $(this);
            if ($this.val() === "") {
                $this.val(value);
            }
        });
    }
});
0

精彩评论

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