Apply a class to a dropdown menu option

I am looking to assign a class to a div based on the selected option from a dropdown menu.

<form onsubmit="return creationMessage(this)"
      target="_blank"
      name="NomForm"
      method="post"
      action="/posting.forum"
      id="am">

  <div class="fond">
    <div class="faction">Presentation</div>
    <select id="ttype" name="ttype" class="obligatoire" focus>
      <option>dresseur</option>
      <option>ligue</option>
    </select>
  </div>
</form> 

And a simple block

<div class="faction"></div>

If the option "dresseur" is selected, I want this :

<div class="faction dresseur"></div>

I tried:

$('select').on('change', function() {
  var colorSelect = $(this).val();
  $('.faction').addClass('colorSelect');
});

Answer №1

just like that

const amForm     = document.querySelector('form#am')
  ,   divFaction = amForm.querySelector('div.faction');

amForm.ttype.oninput = _ => divFaction.className = `faction ${amForm.ttype.value}`;
.dresseur {color: red;}
.ligue { color: blue; }
<form id="am" >

  <div class="faction">Presentation</div>

  <select name="ttype" class="obligatoire">
    <option value="dresseur">dresseur</option>
    <option value="ligue">ligue</option>
  </select>

</form>

Answer №2

Here is a suggested approach:

<div class="group"></div>
<select name="category" class="required">        
  <option selected="selected">teacher</option>
  <option>league</option>
</select>

In your JavaScript file:

$(function(){

          var selected_value = $(".required").val();
          $(".group").addClass(selected_value);


          $(".required").on('change', function(){
            var new_value = $(this).val();
            if(!$(".group").hasClass(new_value)){
              $(".group").addClass(new_value);
            }

          })

        });

This code snippet retrieves the selected value from the dropdown menu and adds it as a class to a div. If the selection changes, it updates the class accordingly.

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

Button-controlled automated presentation

I have devised a method to create an automatic slideshow using JavaScript. However, I am looking to incorporate manual control buttons as well. After adding manual control code, the slideshow seems to be malfunctioning. The provided code below is used for ...

What is the best method to assign jQuery to individual Bootstrap Modals within Thymeleaf?

I am facing the following situation, <script> $(document).ready(function (){ $("#inputText").hide(); $("#checkboxId").click(function (){ $("#div1").toggle("slow" ...

Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page. Currently, I utilize this method to generate a sing ...

What are alternative methods for creating a two-column form layout that do not involve the use of

When generating the html form, I am looping through the form variables as shown below: {% for field in form %} {{ LABEL }}{{ INPUT FIELD }} The labels and fields are going through a loop. A simple one-column layout can be generated using: {% for field ...

Update the div element without needing to reload the entire page

Is there a way to reload a div tag without refreshing the entire page? I understand this question has been asked before, but I want to make sure I have a clear understanding. <p>click HERE</p> <div class="sample"> <?php functi ...

Is there a way to make document flow disregard the scale attribute?

I am looking to add a unique fly-in animation using CSS, where a specific block will scale from 10 to 1. However, when I implement the scaling, a horizontal scroll bar appears: https://jsfiddle.net/r2a5w7fo/15/ body { font: 10svw sans-serif; text-ali ...

An Uncaught TypeError was encountered because the specified object does not contain the 'fancybox' method

Just starting out with Javascript/jQuery and trying to implement jQuery fancybox, but encountering an error message. Received this error: Uncaught TypeError: Object [object Object] has no method 'fancybox'. Sharing my code below: <!DOCTYPE ...

Null Value Returned When Making an Ajax Post Request

I'm having trouble retrieving the id of the last inserted row after posting via ajax. When I var_dump the result, the function returns HTML instead of the id data. What am I missing here? Note: The save method should return the id of the last inserte ...

Linking Background Images in HTML

Is there anyone who can provide assistance with this question? I am looking for a solution where I can have a link with a background image, placed in a row within a table. Your help would be greatly appreciated. Thank you ...

Implementing drag and drop functionality for objects loaded with GLTF in three.js

Having trouble with loading a gltf object made of multiple elements. When attempting to select and drag the object, only one element can be dragged. Seeking assistance in resolving this issue. var loader = new THREE.GLTFLoader(); loader.load(‘W3030 / W3 ...

Font modification is unsuccessful in Vue-Material

Here is a snippet from my App.vue file where I encountered an issue with changing the font in the md-tabs component, taken from . The CSS line: background: #42A5F5; works perfectly fine, but this one does not: color: #E3F2FD; App.vue: <template> ...

Ways to organize the HTML layout for centering content within a div

Returning to html can be tricky...I often forget the basics. I'm trying to center the spans inside this div. Not sure if my structure is correct, any suggestions are welcome! Check out this jsfiddle link for reference .define_link { b ...

Executing a PHP script with form parameter onSubmit for sending an email

I am in the process of creating a form that will trigger a script and send data to a PHP page before redirecting away from the site upon submission. The main purpose behind this setup is to ensure that a confirmation email is sent to the individual fillin ...

Utilizing jQuery to invoke a function at the conclusion of another function's execution

Can someone explain how jQuery can achieve the following? $('.test').css().otherThing...... etc I'm attempting to accomplish this with prototype: var myPrototype = function () {}; myPrototype.prototype.console1 = function() { console.lo ...

Safari and Chrome render flexbox layouts differently

I am encountering a frustrating issue with my font "History Maps" centering within its title box on Chrome using flexbox, but failing to do so in the Safari browser. For reference: Below is the HTML and CSS code in question: /* Parent elements */ ...

Attempting to enlarge logo or image when cursor hovers over it

Seeking to enhance logo/image size when cursor hovers over it, but facing an issue where it enlarges even on areas outside of the image itself - View Example. I followed a tutorial to achieve this effect, and specified the width as 1024x1024 for the logo/i ...

What is the best way to centralize the storage of my website's header and footer?

Constantly updating headers and footers requires me to manually transfer the code to each web page every time, which is not the most efficient method. I'm considering using a "header" and "footer" div, and using jQuery's $(document).ready functio ...

jquery causing issues with content loading

Greetings everyone, I have been attempting to load content into a div using this tutorial with the help of jQuery. However, I am encountering an issue where when I click on the link <a href="about.html" class="panel">Profile</a> , it loads ...

Struggling to format pictures with instafeed.js

I am currently working on a website section that utilizes instafeed.js to display the three most recent images from an Instagram account. The images are loading correctly, but I need some guidance on how to style them appropriately. Unfortunately, the HTML ...

What is the best way to adjust the footer width to match the sidebar using Bootstrap 5?

Currently working on a Bootstrap 5 template for my website, but being new to it makes it a bit challenging. Specifically struggling with aligning the footer to fit the full width of the sidebar. <!DOCTYPE html> <html lang="en"> <head&g ...