Check out this updated jsfiddle:
var map = {}, $firstOption = $('option:eq(0)');
$('select option').each(function() {
var text = $(this).text();
map[text.toLowerCase()] = {
o:text,
u:text.toUpperCase()
}
});
$firstOption.text($firstOption.text().toUpperCase());
$('select').on('change',function() {
var $selected = $('option:selected'),
text = $selected.text().toLowerCase(),
$siblings = $selected.siblings();
$selected.text(map[text]['u']);
$siblings.each(function() {
var text = $(this).text().toLowerCase();
$(this).text(map[text]['o']);
});
});
What it does is store the original version of the text and the uppercase version of the text of each option
element in a plain object. The original and uppercase versions are accessible by the text of the object in all lowercase (just as a consistent identifier... however, you can make them accessible by whatever key you want.)
When you change the select
element, it sets the text of the selected option
to the uppercase version of its text, and sets its sibling elements' text to the original version of their text.
Update
Added a function that changed the text of the first option
to uppercase by default when the page loads.
Updated Code
Here is an updated jsfiddle, that I think is a bit simpler, and in response to your comment, I have changed it to select whichever is the first option selected when the page loads:
var map = {}, $selected = $('option:selected');
$('select option').each(function() {
var text = $(this).text();
map[text.toLowerCase()] = {
o:text,
u:text.toUpperCase()
}
});
$selected.text($selected.text().toUpperCase());
$('select').on('change',function() {
$('option').each(function() {
var $this = $(this),
text = $this.text(),
bool = $this.is(':selected'),
l = text.toLowerCase(),
u = map[l]['u'],
o = map[l]['o'],
fn = {
'true': function() { $this.text(u) },
'false': function() { $this.text(o) }
}[bool]();
})
});
Used as jQuery Plug-in
Here's the jsfiddle:
(function($) {
$.fn.toggleSelect = function() {
return this.each(function() {
var map = {}, $selected = $(this).find('option:selected');
$(this).find('option').each(function() {
var text = $(this).text();
map[text.toLowerCase()] = {
o:text,
u:text.toUpperCase()
}
});
$selected.text($selected.text().toUpperCase());
$(this).on('change',function() {
$(this).find('option').each(function() {
var $this = $(this),
text = $this.text(),
bool = $this.is(':selected'),
l = text.toLowerCase(),
u = map[l]['u'],
o = map[l]['o'],
fn = {
'true': function() { $this.text(u) },
'false': function() { $this.text(o) }
}[bool]();
})
});
});
}
}(jQuery));
$('#a').toggleSelect();
Simply select a select
element with a jQuery selector (such as $('a')
), and then call toggleSelect
. In the above code, only the first select
element in the jsFiddle has the method applied to it. This method will work with multiple select
elements.