Change the chosen item to uppercase within a dropdown menu using pure vanilla JavaScript

I am trying to achieve a specific effect where the text is uppercase only on the selected option within a <select> element. I came across a solution using jQuery in this article, but I need to convert it to plain JavaScript (vanilla JS).

I have made progress and managed to make the selected value uppercase when an option is chosen. However, the issue arises when selecting another option as the previous one remains uppercase too.

I am struggling with changing the logic to "Capitalise all options EXCEPT the selected option, which I would like to be uppercase".

Any help or advice on how to achieve this would be greatly appreciated.

You can view my current progress in this working Fiddle: Here is a working Fiddle of where I am so far.

Answer №1

Have you considered leveraging CSS for this?

* {
  font-family: arial;
}

select option {
  text-transform: capitalize;
}

select, select option:checked {
    text-transform: uppercase;
}
<select name="title" id="title">
    <option selected="" disabled="">Categories</option>
    <option value="photo-galleries">Photo Galleries</option>
    <option value="photography">photography</option>
    <option value="romeo-juliet">Romeo &amp; Juliet</option>
    <option value="swan-lake">Swan Lake</option>
    <option value="symmetries">Symmetries</option>
</select>

<select name="day" id="day">
    <option selected="" disabled="">Day of the week</option>
    <option value="monday">Monday</option>
    <option value="tuesday">Tuesday</option>
    <option value="wednesday">Wednesday</option>
    <option value="thursday">Thursday</option>
    <option value="friday">Friday</option>
    <option value="saturday">Saturday</option>
    <option value="sunday">Sunday</option>
</select>


An alternative in JavaScript is provided below:

[].slice.call( document.querySelectorAll('option') ).forEach(ucfirst);

document.getElementById('title').addEventListener('change', fn, false);
document.getElementById('day').addEventListener('change', fn, false);

function ucfirst(el) {
    el.innerHTML = el.innerHTML.charAt(0).toUpperCase() + el.innerHTML.slice(1).toLowerCase();
}

function fn() {
    var options  = this.getElementsByTagName('option');
    var selected = options[this.selectedIndex];

    [].slice.call(options).forEach(ucfirst);
    selected.value = selected.innerHTML = selected.innerHTML.toUpperCase();
}

FIDDLE

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

Prevent closure of Bootstrap offcanvas on backdrop click in a Blazor .NET application

Trying to implement an offcanvas window form and ensuring it stays open only when the user clicks the close button. Following client requirements, I need to call the offcanvas window via C# with IJSRuntime injection instead of directly from HTML. Operatin ...

Generating a fresh array by filtering out elements with specific properties using the .map() method

Within my React application, there exists an array containing key value pairs where each pair corresponds to a checkbox. Upon checking the checkbox, the value of the corresponding key switches between true and false. The structure of the data retrieved is ...

When attempting to print a Bootstrap 4 HTML page in Chrome, the browser headers and footers are being clipped

Currently experiencing an issue with printing an HTML page styled using Bootstrap 4 (Bootstrap 3.3.7 works fine) on Chrome where the header and footer are partly covered up. Take a look at this screenshot to see what I mean - the date, title, and file/url ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

Tips for assigning a unique identifier to an HTML tag using JavaScript

When appending multiple items in JavaScript like this: data.context = $('<button class="btn btn-primary"/>').text('Upload') .appendTo('#fileTableId') .click(function () { ...

Mastering the art of Promises and handling errors

I've been tasked with developing a WebApp using Angular, but I'm facing a challenge as the project involves Typescript and asynchronous programming, which are new to me. The prototype already exists, and it includes a handshake process that consi ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

Exploring the possibilities of retrieving Cognitive data from Lambda events using Node.js and Typescript

import { APIGatewayEventDefaultAuthorizerContext, APIGatewayProxyEvent, any } from 'aws-lambda'; export async function myHandler(event: APIGatewayProxyEvent, context: APIGatewayEventDefaultAuthorizerContext,): Promise<any> { console.log( ...

how do I modify my JavaScript code to achieve the desired outcome

How can I program a button to disable after being pressed 10 times in less than a minute, but continue counting if not pressed for 1 minute? function buttonClicked() { if (totalCount + accCounter > 9) { document.getElementById("btn").disabled = ...

What are your strategies for designing a website specifically for mobile users?

Today, most modern smartphones come with 720p or 1080p resolution screens. This means that even on smaller screens, like a 4-inch display on a Galaxy s3, we can still view all the text and GUI elements (such as email textboxes) on a website when we first o ...

The premature reveal of the back side in the Kendo UI flip effect on Internet Explorer

Currently, I am in the process of creating a BI dashboard for a business application using JavaScript Kendo UI version v2014.1.416. Unfortunately, I have encountered an issue with certain visuals while testing on IE11. I must mention that due to practical ...

Vue: Clear the current form selection with a button click

<b-row class="mb-3"> <b-col> <div class="float-right"> <b-form-select v-model="selected" :options="options" ></b-form-select> ...

Elements are receiving CSS properties from other elements within the same component

I'm encountering an issue with my components: 1. I cannot seem to style html and body in signin.component.css for some reason. The workaround I found was using: encapsulation: ViewEncapsulation.None ==> This works perfectly However, when I switch ...

Does Typescript not provide typecasting for webviews?

Typescript in my project does not recognize webviews. An example is: const webview = <webview> document.getElementById("foo"); An error is thrown saying "cannot find name 'webview'". How can I fix this issue? It works fine with just javas ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

The websocket connection to the production host has encountered issues, while it operates smoothly on localhost within Django

I successfully integrated a websocket connection for real-time updates in my Django application. The issue arises when I try to host the application on a public server, as it fails to connect. I am using Daphne server for hosting. Below is a snippet of my ...

Retrieving data from router in Angular

I have been working on a web application using Angular, and I have implemented a fixed header in the index.html file. The header appears on every page, with content injected through a ui-view. However, I now want to display this header only after the user ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

Having trouble making the JavaScript mouseenter function work properly?

Hi there, I'm having trouble with this code and I can't figure out why it's not working. $('#thumbs > li').mouseenter(function() { $(this).find("div").fadeIn(); }).mouseleave(function(){ $(this).find("div").fadeOut(); ...