Modify CSS according to the selected value from a dropdown menu

I have a form in which users can select options, and based on their selection, certain questions need to be hidden. I am looking for a way to use jQuery to detect when a specific option is chosen and then modify the CSS of the page accordingly.

<select>
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="mercedes">Mercedes</option>
   <option value="audi">Audi</option>
</select>

Answer №1

From what I gather from your brief explanation, you are looking to perform a certain action based on the user's selection in a dropdown menu, which triggers an event called onchange. Below is a sample code snippet for you:

<select onchange="somefunction($(this).val())">
 <option value="1">Option 1</option>
 <option value="2">Option 2</option>
 </select>

<script>
  function somefunction(value){
     if(value == 1){
      $("body").css("background-color","red");
     }
     if(value == 2){
       $("body").css("background-color","yellow");
     }
  }
   </script>

Answer №2

It seems like your question could use some clarification, but here's my interpretation:

 let choice = $('#selectID option[value=""]').prop("selected", true);

 if (choice....") {
     // apply CSS styles
 }

You can also retrieve the value / text in this way:

<select id="car_brand">
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="mercedes">Mercedes</option>
   <option value="audi">Audi</option>
</select>

<script>
   const section = document.getElementById("car_brand");
   let choice_val = section.options[section.selectedIndex].value;
   let choice_text = section.options[section.selectedIndex].text;
 </script>

You can enhance the above by adding an onchange event to the select element.

<select id="car_brand" onchange="filterBrand(this)">

Adjusting CSS:

In JavaScript:

document.body.style.backgroundColor = "blue";

In jQuery:

$("body").css("background-color","blue");

Fiddle

CSS manipulation example with onchange:

http://jsfiddle.net/2Hx1nRp/

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

What is causing this error to appear in Next.js? The <link rel=preload> is showing an invalid value for `imagesrcset`

I've got a carousel displaying images: <Image src={`http://ticket-t01.s3.eu-central-1.amazonaws.com/${props[organizationId].events[programId].imgId}_0.cover.jpg`} className={styles.carouselImage} layout="responsive" width={865} ...

Is it possible to input values from a database into this Jquery variable for autocomplete()?

$(function () { var productNames = [ "iPhone X", "Samsung Galaxy", "Google Pixel", "OnePlus", "LG G7", "Sony Xperia", "Huawei Mate", "Xiaomi Redmi", "Motorola Moto", "Nokia Lumia", "Blackberry Key", ...

What could be causing the drop-down menu to have such a jerky transition?

After trying numerous approaches, I am seeking help again. I have managed to create a dropdown menu, but now I'm wondering how to add a transition effect to it. Any suggestions on what changes I should make are greatly appreciated. Below is the code s ...

Troubleshooting problem with CSS aligning <dl> and <dd> tags

Utilizing <dt> and <dd> typically assumes a single line definition for dd. However, in my scenario, I have multiple entries for the definition that I need to correctly display (the exact method will be clarified after reviewing the attached ima ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

"Utilizing the ajaxcontroltoolkit CascadingDropDown feature to trigger a method once the control

On my webpage, I am using a CascadingDropDown control and I am looking to trigger some jQuery actions once the dropdown is populated. As per the guidance provided in the documentation, there is an event called (populated) that can be used for this purpose. ...

Div elements containing identical content and styled in the same manner exhibit distinct dashed borders

After designing a pen with a unique twist, you'll notice that the first div has a border-bottom, while the second has a border-top. What's interesting is that the border on the second div is not the same as the first. Visit this link to see for ...

What is the method for using Selenium in Python to locate elements based on CSS selectors on a webpage?

I'm currently experimenting with using Selenium to scrape the introductory paragraph from Wikipedia pages by utilizing CSS selectors. However, the code I have written seems to only extract paragraphs from the main web page, https://en.wikipedia.or ...

Symfony AJAX Autocomplete

I am encountering difficulty while setting up an autocomplete form for city names. Although I have verified that the JSON response is being received (checked in Firebug), I am unable to get the autocomplete functionality from jQuery UI to work. The files ...

Responsive SmoothSlider

Need help fixing the responsive breadcrumbs in my slick slider. The slick-content-slider is taking a strange height and I want to ensure that every div remains on the same line. Thank you in advance! $('.slick-content-slider').slick({ slides ...

Unresponsive Hover Effect on iPad

I've implemented a hover effect on the menu for my one-page website. When a user hovers over a navigation link on desktop, the color changes to #ed1c28. .nf-navbar .navbar-collapse a:hover { color: #ed1c28; } Additionally, when a user clicks on a ...

Is it possible to use JavaScript to forcefully transition a CSS keyframe animation to its end state?

One dilemma I am facing involves CSS keyframe animations triggered by scroll behavior. When users scroll too quickly, I would like JavaScript to help send some of the animations to their 'finished/final' state, especially since the animations bui ...

Tips for displaying multiple rows horizontallyALLOWING multiple rows to appear horizontally can be achieved by

This is a demonstration of my desired outcome https://i.sstatic.net/UErvL.png However, I am currently only able to show one product per row. I have attempted the following approach, but it is not functioning as expected. <ol> <?php $no = 1; ...

Is it possible to make side elements expand to occupy the remaining screen space beyond the container?

This is what it's supposed to look like: The goal here is to have the red element on the left expand to fill the remaining space beside its content, as well as the grey on the right. I am utilizing bootstrap which means the center elements occupy 117 ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Splitting a Multidimensional Array in JavaScript into Two Separate Arrays

I received an array from an ajax call (data) that I need to split into two parts: An alert showing the data reveals: [[200326,150000],[200327,150000],[200328,150000],[200329,150000],[200330,160000],[200331,320000]] I attempted to extract the dates (fi ...

Implementing color transitions in javascript

Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I&apo ...

The cookie message will only be displayed once after clicking the submit button

Can someone assist me with setting up a cookies message popup? I want the message to only display once per user click on accept. Here is the code snippet: https://jsfiddle.net/bz8ur3wu/1/ $(document).ready(function(){ $("button").click(function(){ ...

Can a single controller function in ASP.NET MVC4 be used to send back two arrays to the view?

Continuing from my previous query here, I am working with a model called SchoolTestsPerModulePerStudent which looks like this: public partial class SchoolTestsPerModulePerStudent { public long StudentID { get; set; } public long ModuleID { get; se ...

Checking the Validity of URLs in AngularJS

When validating a value provided by users for a URL field, the system consults platforms like Facebook, Twitter, and Google+. Does anyone have suggestions for the best way to validate this input? We are currently using the following pattern: /((?:https? ...