Question

I have a bunch of drop downs and I want to know the most efficient way to determine if the drop down just changed is the last visible drop down in the list. Right now this code just checks if the one just changed is the last one not the last visible one.

<div id="dropdownArea">
   <div>
      <select id="select1"></select>
   </div>
   <div>
      <select id="select2"></select>
   </div>
   <div style="display: none;">
      <select id="select3"></select>
   </div>
   <div style="display: none;">
      <select id="select4"></select>
   </div>
</div>

target = the select that just changed;

if($(target).parent().index() === $("#dropdownArea").children().length - 1){
   //do stuff
}

New code:

var dddivs = $("#dropdownArea").children().filter(":visible");
if($(dddivs).index(target) === $("#dropdownArea").children().length - 1){
   //do stuff
}

Will that work? Is there a more efficient way?

Was it helpful?

Solution

You can use .is to test for equality of jQuery objects. Other than that I would append .last to get the last visible select and pass a selector to the .children method to remove the need for a filter:

var lastVisibleSelect = $("#dropdownArea").children(":visible").last();
if($(this).parent().is(lastVisibleSelect)){
   //do stuff
}

OTHER TIPS

You can do this:

var $selects = $('select');

$selects.on('change', function () {
  var $select = $(this);
  var startIndex = $selects.index($select);
  var visibleNextSiblingsLength = $selects.slice(startIndex + 1).filter(':visible').length;
  if (visibleNextSiblingsLength === 0) {
    console.log('You just changed the last visible select');
  }
});

Though RGraham's is probably better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top