Designing the closed view dropdown box

Demo

Issue: Hello there, please take a look at my code snippet. I am trying to have all options in a dropdown menu displayed in lowercase except for the selected option which should be capitalized when viewed in a closed state.

Solution:

  <select>
    <option>One</option>
    <option>Two</option>
  </select>

$("select").change(function () {
               $(this).find("option").text(function (i, text) {
                     return $(this).is(":selected") ?  text.toUpperCase() : text.toLowerCase();
               });
            })

Is this achievable? If so, do you have any suggestions on how to accomplish this? If not, could you kindly provide an explanation. Please refer to the attachment as it shows the desired appearance of the closed view.

Answer №1

An unconventional workaround has been implemented in this code snippet: when the dropdown list is closed, the selected option appears in uppercase, while all options are displayed in lowercase when the dropdown list is open.

For a demonstration of this workaround, check out the Fiddle.

var wasSelected = false;

$("select").click(function()
{
    if (!wasSelected) //on dropdown open
    {
        $(this).find("option:selected").text(function(i, text)
        {
            return text.toLowerCase();
        });
    }
    else
    {
        wasSelected = false;
    }
});

$("select").change(function()
{
    $(this).find("option").text(function(i, text)
    {
        return $(this).is(":selected") ? text.toUpperCase() : text.toLowerCase();
    });
    wasSelected = true;
});

$("select").change(); //initial dropdown formatting
$("select").click(); //initial dropdown formatting

An update has been made to address some issues with additional workarounds:

Check out the updated version on Fiddle.

var wasSelected = false;
var wasClicked = false;

$("select").click(function()
{
    if (wasClicked)
    {
        onClose($(this));
    }
    else if (!wasSelected)
    {
        $(this).find("option:selected").text(function(i, text)
        {
            return text.toLowerCase();
        });
        wasClicked = true;
    }
    else
    {
        wasSelected = false;
    }
});

$("select").change(function()
{
    wasSelected = wasClicked;
    onClose($(this));
});

$("select").blur(function()
{
    onClose($(this));
});

function onClose(jElement)
{
    jElement.find("option").text(function(i, text)
    {
        return $(this).is(":selected") ? text.toUpperCase() : text.toLowerCase();
    });
    wasClicked = false;
}

$("select").change();

Answer №2

    $('option').each(function(index){
    if(!$(this).is(':selected'))
        $(this).text($(this).text().toLowerCase());
    });

Please review the fiddle provided with the code above. Is this what you were looking for?

View the fiddle here: Dropdown text transformation

Answer №3

It seems like your code is functioning properly. If you want the pre-selected value to be displayed in uppercase when the page loads, you'll need to invoke the code on jQuery's document ready event.

You can implement the following code:

$("select").change(function () {
  modifySelectBox();
})

jQuery(document).ready(function(){        
    modifySelectBox()
})

function modifySelectBox() {
     $("#myselbox").find("option").text(function (i, text) {
         return $(this).is(":selected") ?  text.toUpperCase() : text.toLowerCase();
     });
}

HTML

<select id="myselbox">
    <option selected="selected">One</option>    
    <option>Two</option>
    <option>Three</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Identify and Print a Specific Property in a JSON Object using Node.js?

Hey there, I'm having trouble extracting the trackName from the JSON object provided here. I've tried accessing it using this code: console.log(res.text.results[0].trackName); but unfortunately, I keep getting this error message: TypeError: Cann ...

Access the Windows taskbar while the browser is in a minimized state

I am developing an MVC Web Application for a time tracking system. I need to find a way to display daily target and completed target information of the user in the Windows taskbar when the browser window is minimized... Can anyone please help me with this ...

What are the steps to check Drag and Drop functionality using Selenium IDE?

I've been working on implementing tables with jQuery UI's sortable feature, but I'm struggling to come up with a way to test it using Selenium IDE. After searching for a solution, I came across this helpful post: How to test a JQuery UI Sor ...

Guide to stripping HTTP headers from a REST API request using JavaScript

Hey there! I'm currently working on extracting a specific part of the response from the {}. This information is retrieved from the gemini public database, and my goal is to retrieve only the content within the curly braces and store it as a string in ...

Utilizing ng-change to trigger function several times within ng-repeat loop for input elements

Currently, I am experiencing a problem that involves an ng-repeat containing an input with ng-change() inside a directive template. This input is double way bound to a parent object. When I enter text into the input box, everything functions as expected an ...

Execute the JS file to retrieve the initial port available within the npm script

Within my package.json, I have the following script: "dev": "webpack-dev-server --config webpack.dev.js --progress --port ${getPort()}", I've also installed a package called get-port, which allows me to set a default port and ...

Creating an Event Listener for a Published Angular Elements Web Component

Note: The Web Component mentioned here is exported from Angular using Angular Elements and differs from traditional Angular components Experimenting with Angular Elements led to the creation of an NgFor component that loads the JSON file provided below. ...

Styling with CSS for an associative array with multiple columns

How can I modify this PHP function to display its output within a scrolling text box with word wrap in CSS? <?php function prettyPrint( $my_array ) { if (is_array($my_array)) { echo "<table style=border=0 cellspacing=2 cellpadding ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

Open space on responsive website causing layout issue

I need help troubleshooting some code for a responsive website. When I shrink the screen and an item goes "under" another one instead of next to it, it creates a large gap that I want to avoid. Ideally, I would like the items to shrink up to a certain mini ...

Send array as data in an AJAX request using the $.ajax() method

I attempted the following code snippet but was unable to retrieve an array list. It is returning 'null' var data=[]; data[0] = '1'; data[1] = '2'; $.ajax({ url: '@Url.Action("AddFreque ...

Enhancing an existing header by integrating bootstrap for collapse functionality and incorporating bootstrap animations

This is a fresh query that was briefly mentioned in my prior post here to avoid duplicating the code. I'm seeking advice on how to animate the collapsible navbar, as the current code is functional but lacks animation when collapsed. Would this involv ...

What is the most effective way to adjust an adaptation: adjusting the max-width or the font-size?

Being new to coding, I'm still in the practice stage. However, I've noticed that whenever I shrink the screen size, the text starts misbehaving. How can I address this issue? Here is a specific example of the problem: https://i.sstatic.net/QZlN ...

Should the index.js file in Next.js serve as the homepage or solely as the initial starting point?

Should I integrate my homepage directly into the index.js file, or create a separate "home-page.js" file in the pages directory? Is index.js just for initializing the application, or can it serve as a standalone page? Alternatively, should I have index.j ...

The error message "Cannot read property 'addEventListener' of undefined" occurred while trying to register the service worker using `navigator.serviceWorker.register('worker.js')`

I'm grappling with a JavaScript issue and need some help. You can find the demo of the functioning script by the author right here. I've implemented the same code as displayed on his demo page. I've downloaded the worker.js file and ...

Having trouble retrieving the accurate height value for the UIWebView

Currently, I am attempting to retrieve the value of a UIWebView using the following approach: var webview = self.articleContent println(webview.frame.size.height) // This outputs 300 // Now rendering the w ...

Validation of minimum and maximum character length using jQuery

I am trying to implement a validation that requires a minimum length of 8 and a maximum length of 14 characters. Can anyone guide me on how to achieve this? Here is the code snippet in HTML: <input type="text" name="354" id="field"> And here is th ...

Extending EJS partials using jQuery

I am currently exploring the integration of JQuery to dynamically add an EJS partial. My goal is to enable infinite scrolling within a table - I have opted for EJS to render the rows of the table as partials and leverage more EJS to exhibit the variables p ...

Creating internal utility functions in Angular without exporting them as part of the module can be achieved by following a

Currently, I'm in the process of creating an angular module called MyModule. This module includes several sub-modules. angular.module('MyModule', [ 'MyModule.SubModule1', 'MyModule.SubModule2', 'MyModule.SubMo ...

AJAX Submission: Receiving a Successful Response (Status 200) Despite an

I've encountered similar questions on this topic, but none have been able to provide a solution for my specific issue. The problem I'm facing is related to submitting a form within a JQuery Modal using AJAX. Despite receiving a status 200 respon ...