What is the chosen value based on the action taken?

I am looking to change the color of a select box and its row based on the selected value in the select box. I have three select boxes with three options each. How can I implement color changes for each option selected in each select box?

.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>

<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>
  </div>
</div>
I want the result to look like this image https://i.sstatic.net/Bpe03.png I'll take care of customizing the select box, but I need help adding specific classes for different colors.

Answer №1

To accomplish this, utilize JavaScript (specifically jQuery) and listen for the change event on a select element. Then use the closest() method for selecting the parent element as shown below:

$('select').on('change', function() {
  var value = $(this).find(':selected').text();
  if(value == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if(value == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});

See the live example snippet provided below:

$('select').each(function() {
  var text = $(this).find(':selected').text();
  if(text == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if (text == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});

$('body').on('change', 'select', function() {
  var value = $(this).find(':selected').text();
  if(value == 'Primary') {
    $(this).parent().closest('.row').addClass('primary');
    $(this).parent().closest('.row').removeClass('secondary optional');
  } else if(value == 'Secondary') {
    $(this).parent().closest('.row').addClass('secondary');
    $(this).parent().closest('.row').removeClass('primary optional');
  } else {
    $(this).parent().closest('.row').addClass('optional');
    $(this).parent().closest('.row').removeClass('primary secondary');
  }
});
 

$('#btnAddEmpField').on('click', function(){
$('.emp-customize-form').append("<div class='row secondary'>\
  <div class='col'>\
    <select id='impSelect1'>\
      <option value='primary'>Primary</option>\
      <option value='secondary' selected>Secondary</option>\
      <option value='optional'>Optional</option>\
    </select>\
  </div>\
</div>");
})
                    
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

.primary {
  color: white;
  background-color: red;
}

.secondary {
  color: white;
  background-color: green;
}

.optional {
  color: white;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="emp-customize-form">
  <div class="row">
    <div class="col">
      <select id="impSelect1">
        <option value="primary" selected>Primary</option>
        <option value="secondary">Secondary</option>
        <option value="optional">Optional</option>
      </select>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <select id="impSelect2">
        <option value="primary">Primary</option>
        <option value="secondary" selected>Secondary</option>
        <option value="optional">Optional</option>
      </select>
    </div>
  </div>

  <div class="row">
    <div class="col">
      <select id="impSelect3">
        <option value="primary">Primary</option>
        <option value="secondary">Secondary</option>
        <option value="optional" selected>Optional</option>
      </select>
    </div>
  </div>
</div>

<span id="btnAddEmpField">add</span>

We trust that above information proves beneficial!

Answer №2

Utilize a color dictionary to dynamically change the color based on the selection in the dropdown menu. Take a look at the following code snippet:

var color = {'primary':'red', 'secondary': 'blue', 'optional':'gray'};

$('.impSelect').click(function(){
$(this).css('background-color', color[$(this).val()]);
});
$('.impSelect').click();
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col">
    <select id="impSelect" class="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col">
    <select id="impSelect" class="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>

<div class="row">
  <div class="col">
    <select id="impSelect" class="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>
  </div>
</div>

Answer №3

Ensure that the addClass function is executed when the select button's function is changed. To add a class to the parent element, target the row class using the closest() jQuery function.

$('.row').on('change', 'select', function(){
$(this).attr('class','').addClass($(this).val()).closest('.row').attr('class','row').addClass($(this).val())
})
$(function(){
$('.row select').each(function(){
$(this).attr('class','').addClass($(this).val()).closest('.row').attr('class','row').addClass($(this).val())
})
})
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}
.primary{
background-color:red;
}
.optional{
background-color:blue;
}
.secondary{
background-color:#aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>

<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>
  </div>
</div>

Answer №4

To achieve this, one method is to attach a change event listener to the desired select elements. In the code snippet below, I have applied it to all select elements, but you can target them using CSS classes or descendant selectors as well.

Next, you can define CSS classes to provide specific styles to each select element. In the example, I have named the CSS classes according to the values they represent. Therefore, including the class primary in a select would result in a red background with white text color.

select.primary {
  background-color: red;
  color: white;
}

So whenever the value inside the select changes, you simply remove any existing classes and apply the new class accordingly.

$("select").on("change", function() {
  // Clear any previous classes.
  $(this).attr("class","");

  // Apply the new class based on the selected value.
  var value = $(this).val();
  $(this).addClass(value);
});

// Initial application of colors.
$("select").each(function(){
  var value = $(this).val();
  $(this).addClass(value);
});
.row {
  padding: 10px 20px;
  background: purple;
}

select {
  width: 100px;
  height: 40px;
  background: #eee;
  border: 1px solid #333;
}

select.primary {
  background-color: red;
  color: white;
}

select.secondary {
  background-color: purple;
  color: white;
}

select.optional {
  background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary" selected>Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional">Optional</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary" selected>Secondary</option>
      <option value="optional">Optional</option>
    </select>

  </div>
</div>

<div class="row">
  <div class="col">
    <select id="impSelect">
      <option value="primary">Primary</option>
      <option value="secondary">Secondary</option>
      <option value="optional" selected>Optional</option>
    </select>
  </div>
</div>

Answer №5

  1. Define different styles for select options by creating corresponding classes in your CSS file. For example:

    .important { background: red; color: white;}
    .secondary { background: blue; color: white;}

  2. Use jQuery to apply the selected class when a user changes the select dropdown

    $(document).ready(function(){
       $('select').on('change', function(){
          var thisSelect = $(this);
          var optionSelected = thisSelect.find("option:selected");
          var optionClass = optionSelected.attr('class');
          thisSelect.removeClass().addClass(optionClass);
       });
    });

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

Separation distance between each row utilizing Skel

Currently, I am working with the Skel grid system to structure my layout, but I am facing difficulty in adding space between rows. Here is a snippet of my HTML code: <style> .element{ border: 1px solid black; } </style> <!--[...]!--> &l ...

Can you explain how the Facebook Like button code functions and how I can create a similar feature on my own platform?

I have a website with 250 different items, each containing its own Like button using the standard Facebook "Like" code: div class="fb-like" data-href="http://www.mywebpage.com/myproductpage" data-send="false" data-layout="button_count" data-width="80" dat ...

Does renaming a sub-directory in the static directory of an IntelliJ Spring Boot project cause any changes?

I'm a newcomer to IntelliJ and I've been using it to develop a Spring Boot application. Right now, my project structure looks like this: https://i.sstatic.net/7A7jb.png My goal is to set up a "css" directory within the "static" directory under ...

Pre-set value in input field

Seeking recommendations on how to create an input field with a fixed initial value while meeting the following criteria: Avoid using the <input> element as it is already in use. Capable of handling values of any length. For example: Appreciate an ...

Select a checkbox within a gridview using jQuery

My gridview has two checkbox columns - one for selection and the other for setting a property like "add to favorite". The checkboxes are defined within the Item Template in the code-behind. However, it is not very user-friendly to have users check two boxe ...

Unable to receive WhatsApp messages through chat API in PHP

I'm currently utilizing a chat API with PHP to send and receive Whatsapp messages. While I am able to send messages successfully, I am encountering difficulties in receiving messages. For reference, please check out: Below is the snippet of my PHP c ...

Align the text to the center beneath the image using Jquery's append function

I am looking to showcase a collection of fruits and vegetables through images, with the names displayed centered underneath each image. Additionally, I want to implement jQuery append functionality so that the names only appear when a specific button is cl ...

Creating Dynamic Bootstrap 4 Forms with Two Columns

I have a user registration form (Bootstrap 4 - in Razor Template) Depending on the user's selections, I will hide certain parts of the form. The registration form consists of two steps, and this is the second step. If a user selects a country withou ...

Ways to customize the appearance of the navigation bar when hovering

Is there a way to customize the hover state of a navigation bar? I would like to highlight certain menu items in a different color when they are hovered over, such as making "menu1" stand out. Any help with this would be greatly appreciated! <div cla ...

What are the common practices for UI bindings in JavaScript and AJAX applications?

Background Information Currently, I am in the process of developing a traditional web application with most forms operating through AJAX. I am facing challenges in connecting the user interface to the model. As of now, I have to explicitly: Specify the ...

The server files have had all line breaks removed

Currently I am working with Wordpress and facing an issue. When I upload my project file to the live server, all content within "styles.css" gets compressed into a single line. The same thing happens with the content inside "header.php" and "footer.php", ...

The JavaScript date picker is malfunctioning in the HTML editor, but it functions properly in Fiddle

I have a working format available in a JS fiddle. Here is the code I have used on my demo site: I created a new folder named "js" and placed datepicker.js inside it, then linked it in my HTML like this: <script type="text/javascript" src="js/datepicke ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Is the input text returning NULL on postback?

Could someone please explain why the id value of the checkbox 'userId' is coming back as null during the POST request? <input type='checkbox' onclick='$("#userId").val("@user.Id"); return true; '/> @using (Html.BeginFo ...

Which is more advantageous in this scenario: using .fail() or .timeout()?

When it comes to handling timeouts on my $.ajax() calls for a jQueryMobile project, I have discovered two potential methods. The .fail() function appears to be the more generic option: if the call fails for any reason, an error stack is returned and then ...

When the form is submitted, the value is not refreshed if the button is exited

I need to have a form where the save button is positioned outside of the form elements. However, when I move it elsewhere, the form does not refresh. <form ng-submit="save()" action="" name="addInv" novalidate> <div class="col-md-10 ...

Is there a way to prevent automatically scrolling to the top of the page when submitting a form?

Resolved! By enclosing the input tag within an anchor tag, the issue has been resolved. The question may appear confusing at first, so let me provide some clarification. I created a mail form using PHP. This form is located at the bottom of the page. Whe ...

Tips for avoiding selecting only the day on the mat-datepicker

I am facing a challenge in my project where users need to select only the year and month, excluding the specific day of the month. Any suggestions on how to achieve this? Any help would be greatly appreciated! -------------------------------------------- ...

Implementing Jquery after async ajax refresh in an asp.net application

My ASP.net page is heavily reliant on jQuery. Within this page, I have a GridView placed inside an UpdatePanel to allow for asynchronous updates. <asp:GridView ID="gvMail" runat="server" GridLines="None" AutoGenerateColumns="false" ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...