832ed6ace46d61032151f4e1864c057f

Could be written in plain javascript or prototype (or jQuery).

var next = false;
for (var i = 0; i < el.options.length; i++) {
  if (next) {
    next = false;
    el.options[i].selected = true;
    break;
  }
  if (el.options[i].selected) {
    el.options[i].selected = false;
    next = true;
  }
}
if (next) {
  el.options[0].selected = true;
}

Refactorings

No refactoring yet !

23132e1aa8457e11b243a43b578d51dc

Simo Niemelä

January 25, 2009, January 25, 2009 21:10, permalink

2 ratings. Login to rate!
jQuery.fn.checkNext = function() {
  if (this.is(':last-child') && this.is(':selected')) {
    this.attr('selected', false).parent().children(':first').attr('selected', true);
  } else if (this.is(':selected')) {
    this.attr('selected', false).next().attr('selected', true);
  }
}

$(function(){
  $('select#el > option[selected]').checkNext();
});
5071c5b861341c0dcfcf6ac86327701f

Tien Dung

January 26, 2009, January 26, 2009 01:22, permalink

1 rating. Login to rate!

Simo refactoring is great. Just want to remove some code from checkNext function.

jQuery.fn.checkNext = function() {
  if (this.is(':selected')) {
    this.attr('selected', false);
    var next = this.is(':last-child') ? this.parent().children(':first') : this.next();
    next.attr('selected', true);
  }
}
3a97ad2110290131f3da65022327635a

fluminis

March 3, 2009, March 03, 2009 16:16, permalink

No rating. Login to rate!

in plain javascript...

function selectNext(id) {
  var s = document.getElementById(id);
  if (s.selectedIndex+1 < s.options.length) {
    s.selectedIndex = s.selectedIndex + 1;
  }
}
C5283f5f6e2659a1b4e7ddb87eca0640

Peter Kaleta

May 27, 2009, May 27, 2009 15:22, permalink

No rating. Login to rate!

Tien - great code , but when operating on select there can be <oprgroup> tag. So I let myself to tiny-refactor your code. Also make it possible to call on select itself , not on options from selector.

jQuery.fn.checkNext = function() {
  var selected_option = this.find('option:selected');
    selected_option.attr('selected', false);
    var next = selected_option.is(':last-child') ? this.find('option:first') : selected_option.next();
    next.attr('selected', true);
  }
}

$(function(){
  $('select').checkNext();
});
C5283f5f6e2659a1b4e7ddb87eca0640

Piotr Kaleta

May 27, 2009, May 27, 2009 15:27, permalink

No rating. Login to rate!

Sorry for double post but i added code for situation in which :

<optgroup>
<option></option>
<option></option>
</optgroup>
<optgroup>
<option></option>
<option></option>
</optgroup>

$.fn.selectNextOption = function(){
		var selected_option = $(this).find('option:selected');
		selected_option.attr('selected', false);
    	var next = selected_option.is(':last-child') ? $(this).find('option:first') : selected_option.nextAll('option:first');
    	next.attr('selected', true);
  	}

Your refactoring





Format Copy from initial code

or Cancel