1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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 !
Simo Niemelä
January 25, 2009, January 25, 2009 21:10, permalink
1 2 3 4 5 6 7 8 9 10 11
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(); });
Tien Dung
January 26, 2009, January 26, 2009 01:22, permalink
Simo refactoring is great. Just want to remove some code from checkNext function.
1 2 3 4 5 6 7
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); } }
fluminis
March 3, 2009, March 03, 2009 16:16, permalink
in plain javascript...
1 2 3 4 5 6
function selectNext(id) { var s = document.getElementById(id); if (s.selectedIndex+1 < s.options.length) { s.selectedIndex = s.selectedIndex + 1; } }
Peter Kaleta
May 27, 2009, May 27, 2009 15:22, permalink
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.
1 2 3 4 5 6 7 8 9 10 11
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(); });
Piotr Kaleta
May 27, 2009, May 27, 2009 15:27, permalink
Sorry for double post but i added code for situation in which :
<optgroup>
<option></option>
<option></option>
</optgroup>
<optgroup>
<option></option>
<option></option>
</optgroup>
1 2 3 4 5 6
$.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); }
Could be written in plain javascript or prototype (or jQuery).