What is the best way to append a single class while also ensuring any previously added classes are removed?

How can I apply the selected class and remove any previously selected classes?

<html>
    <select name="Button-Style" id="Button-Style" style="width:100%;">

     <option value="Sun-Flower">Sun Flower</option>
     <option value="orange-flat">Orange Flat</option>


   </select>


    <script>
    $(document).ready(function(){
        $('#Button-Style').change(function(){
          if($(this).val() == 'Sun-Flower'){
             $("#" + id).removeClass().addClass('sun-flower-button');
              }
          else if($(this).val() == 'orange-flat'){
             $("#" + id).removeClass().addClass('orange-flat-button');
              }



          else{

              }
        });
    });
    </script>
</html>

I only want one class to be applied at a time.

Answer №1

If you want to achieve this using javascript, you can follow the example below.

            $('.selected_check').change(function () {

                if ($(this).is(":checked")) {
                    var x = $(this).closest('tr').prop('id');
                    var id = "#" + x;
					
                    // Remove td_bgcolor class and add highlight_row class
                    $(id).removeClass('td_bgcolor');
                    $(id).addClass('highlight_row');
                } else {
                    var y = $(this).closest('tr').prop('id');
                    var id = "#" + y;
                    
                    // Remove highlight_row class and add td_bgcolor class
                    $(id).removeClass('highlight_row');
                    $(id).addClass('td_bgcolor');
                }

            });

You can simply use removeClass and addClass functions for this purpose. Happy coding!

Answer №2

To utilize the removeClass() function in jQuery, follow these steps:

For instance;

Begin with the HTML code:

<div id="adiv" class="1st-class"></div>

Next, use jQuery as shown below;

$("#adiv").addClass("2nd-div");             // This will add 2nd-class to the div

$("#adiv").removeClass("1st-div");          //This will remove the 1st-class from the div.

If you wish to remove all previously added classes, simply execute;

$("#adiv").removeClass();                   //removeClass without any argument removes all classes  

Answer №3

I'm struggling a bit to grasp your query, but I believe I have the main idea.

Imagine you have this HTML structure:

<div class="menu">
  <div class="menu--option">Option 1</div>
  <div class="menu--option">Option 2</div>
  <div class="menu--option">Option 3</div>
</div>

If we want to ensure that only the clicked option has the class s-active, we can use the following code snippet:

// Listen for click events on menu options.
$("menu--option").click(function () {

  // Remove 's-active' from all menu options.
  $("menu--option").each(function () {
    $(this).removeClass("s-active");
  });

  // Add 's-active' to the clicked element.
  $(this).addClass("s-active");
}

I hope this explanation proves helpful!

Answer №4

Here is one way to write the code!

 $('#Button-Style').on('change', function(){
$(this).removeClass();
if($(this).val()=="your_option_value"){
$(this).addClass("new_class");}
}

Answer №5

Uncertain about the element you are adding a class to, but you can use removeClass() without any parameters to remove all previously applied classes and then add your desired class using addClass()

   if($(this).val() == 'sun-flower'){
       $("#$id>input").removeClass(); // Remove all previous classes ... make sure to verify the selector 
       $("#$id>input").addClass('sun-flower-button');
         }
          else if($(this).val() == 'orange-flat'){
              $("#" + id).removeClass();
             $("#" + id).addClass('orange-flat-button');
              }

You could also consider passing the class name directly from the option values in the select item. This way, no extra if conditions are necessary.

<select name="Button-Style" id="Button-Style" style="width:100%;">
     <option value="Sun-Flower-button">Sun Flower</option>
     <option value="orange-flat-button">orange-flat</option>
</select>

In jQuery:

$('#Button-Style').change(function(){
  var className = $(this).val();
  $('#inputElement').removeClass();
  $('#inputElement').addClass(className);        
});

Answer №6

For those looking to clear out existing classes and implement a fresh one, jQuery provides the handy toggleClass function.

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

Sending an array from JavaScript to PHP and then back to JavaScript

I have a task to transfer an array from one webpage to a PHP page for it to be saved in a file, and then another webpage has to retrieve that array from the file. Currently, I have an array in JavaScript containing all the necessary information: JavaScri ...

Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted. <script type="text/ng-template" id="mobileSearchPanel"> <form> ...

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

The Art of HTML and CSS Layouts

My code is displaying a layout where the 'Login or Signup' link is not aligning to the right side of the page as intended. Can anyone help me with this issue? HTML <header> <h1>Heading</h1> <p>A clean, minimal, gri ...

"Customizing a footer to resemble a bootstrap nav-bar: A step-by-step guide

My situation involves the need to have a footer that functions similarly to a navbar. I want to be able to hide the list items of a ul list by clicking on a custom button, similar to the functionality of the bootstrap hamburger menu. Is it possible to use ...

Troubleshooting a VueJS Problem: Updating $data in the mounted hook

Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

Currently, my main focus is on finding a solution to adjusting the background color of the div element named *topnav* to properly match the width of the

I'm having trouble adjusting the width of the topnav background color to fill the entire page without any gaps. I hope that makes sense. Let me know if you need more information. Page displaying gap: Here is the HTML and CSS code: body {background ...

Unable to move cursor in contenteditable section

I am currently working on developing a rich text editor in React, but I have encountered an issue that has me stuck. The problem I am facing is that as I type each character, the insertion point does not update accordingly, causing the cursor to remain stu ...

Tips for simulating an ajax request in a Jasmine test

Check out my code snippet below: function sendRequestData(url, urlParameters) { $.ajax({ url : url, method : 'POST', headers : { 'Accept' : 'application/json' }, contentType : 'application/js ...

Purge precise LocalStorage data in HTML/JavaScript

How can a specific item in the localStorage be cleared using javascript within an html file? localStorage.setItem("one"); localStorage.setItem("two"); //What is the method to clear only "one" ...

Show specific modal or image depending on various criteria

Seeking guidance on how to achieve the following tasks in a simple manner as my understanding of HTML, Bootstrap, and CSS is basic: 'When radio button #1, radio button #4, and button #2 are clicked, upon submission display modal 1 with an image at a ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

Issue with dropdown list functionality in Internet Explorer not functioning correctly

I am experiencing an issue with my dropdown lists. When selecting an item from the first dropdown list, it should not be available in the second dropdown list. To achieve this functionality, I have implemented jQuery code like the following: $(document).r ...

What is the best way to create shaded areas upon clicking them?

How can I implement shading on areas when they are clicked? Contractor Form (Package One) <area id="39" name ="39" alt="" title="39" href="#" shape="poly" coords="12,204,12,120,138,117,144,72,248,72,252,124,526,125,632,81,668,157,698,149,722,2 ...

What is the process for encoding images in HTML code?

Is there a method to embed a background image directly in the HTML code? For instance: background-image: url(data:image/gif;base64,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX); If I have an image file, can I encode its data and t ...

Generating Arrays of Varying Lengths in ReactJS

When receiving data from the API, I have an array structured like this: [ { "clicks": { "2019-01": [ { "clicks": "194", "type": 0, "user": 19 }, { ...

URL validation RegEx in AngularJs using Javascript

I am looking for the following URLs to return as true other.some.url some.url some.url/page/1 The following URL should be flagged as false somerandomvalue Here is the regex I have been experimenting with so far: /^(?:http(s)?:\/\/) ...

Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class. .my_image_class:hover{ border:3px solid blue; -webkit-box-sizing: border-box; } This makes the images bordered in blue when hovered over, giving a "sele ...