Have only the currently selected and displayed option in a select menu formatted in uppercase

StackOverflow https://stackoverflow.com/questions/21712791

  •  10-10-2022
  •  | 
  •  

Pergunta

Lets say I have a select option list like this

<select>
<option selected>Bear</option>
<option>Tiger</option>
<option>Lion</option>
<option>Porcupine</option>
</select>

When the menu is 'inactive' and simply displaying the selected option, I want it to appear uppercase:

ie  BEAR \/

and when the menu is opened it should keep the options in their native format

Bear
Tiger
Lion
Porcupine 

I know you can style all options to uppercase with css, but then when the menu is opened, all the options will be uppercase.

So I'm thinking jQuery.

Perhaps some replace function.

I've tried something close to this, but can't get it working:

$("select option:selected").text(t.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }))

I've also attached it to a select change event.

Can someone help me pull this all together?

Foi útil?

Solução

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.

Outras dicas

I have written this code for hint based on selected option:

$('select[name="Poradi\[\]"]').tooltip({
    position: {
        my: 'right center',
        at: 'left center'
    },
    content: function(){
        if($(this).find('option:selected').val() == 0 )
        {
            return 'Obrázek nebude zobrazen';
        }
        else
        {
            return 'Obrázek bude zobrazen ' + $(this).find('option:selected').val() + '. v pořadí';
        }
    }
});

Part

$(this).find('option:selected').val()

will call value of option I selected - and your code would be

$(this).find('option:selected').toUpperCase();

or so;

but I don't understand why to convert selected option on uppercase; I think that re-colouring of this option would be much better, mostly if original values are not written in only small caps (small letters).

I suppose that you would like to focus changing of text into uppercase on change - and then all code would be (for example):

$('select[name="???"]').change(
    function(){
        $(this).find('option:selected').css('color', '#CFCFCF');});

and

$('select[name="???"]').change(
    function(){
        $(this).find('option:not(:selected)').css('color', '#FFFFFF');});

or

$('select[name="???"]').change(
    function(){
        $(this).find('option:selected').css('text-transform', 'uppercase');});

and

$('select[name="???"]').change(
    function(){
        $(this).find('option:not(:selected)').css('text-transform', 'capitalize');});

or

$('select[name="???"]').change(
    function(){
        $(this).find('option:not(:selected)').css('text-transform', 'none');});

BTW: I am sorry for czech language of texts displayed by script written above.

As @smclark89 writes, it is possible to use also

$('select[name="???"]').change(
    function(){
        $(this).find('option').filter(':selected').css('text-transform', 'uppercase');});

and (thus for re-formatting back to original caps)

$('select[name="???"]').change(
    function(){
        $(this).find('option').filter(':not(:selected)').css('text-transform', 'none');});

Edit:

$('option:selected').each(function(){
    $(this).css('text-transform', 'uppercase' );
});

will set default :selected values transformed on uppercase

$('option:selected').change(function(){
    $(this).css('text-transform', 'uppercase' );
});

will transform values of selected options on uppercase - when they are selected.

But it is displayed only when options are displayed, not else.

Edit: Beware: Probably it will be correct only in some browsers. I found that Opera does not like formatting of elements inside of <select>, when I finished my supertemplate machine and did tests of it. You would find that chosen element has got new style in code, but it will be not displayed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top