Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. I tried using if-else statements but it did not work as expected.

var i = $("li").index( $(this).parent() );

  if ( i === 1 ) {
    $('btn_clear').css('background', 'blue');
  } else if ( i === 2 ) {

View my BOOTPLY demonstration here: BOOTPLY

Answer №1

Make a simple adjustment to your click handlers as shown below:-

$(".products .checkbox, .availability .checkbox").on("click", function(e) {

  var menu = $(this).closest('.dropdown-menu');

  var checkCount = menu.find(':checked').length;

  $('.btn_clear', menu).css('background', checkCount > 0 ? 'blue' : 'grey');
  $('.btn_apply', menu).css('background', checkCount > 0 ? 'green' : 'yellow');

});

This code specifically calculates the number of checked items in the dropdown and changes their color accordingly.

Visit Bootply

Note:

Below is the revised code for the clear handler.

$(".btn_clear").on('click', function (e) {
    e.stopPropagation();
    var menu = $(this).closest('.dropdown-menu');
    menu.find('input[type="checkbox"]').prop('checked', false);
    $('.btn_apply', menu).css('background', 'yellow');
});

Answer №2

To ensure a default color value is always set, you can use the following approach:

var index = $('li').index($(this).parent()),
    // Set the default color for the button.
    color = 'red';

if (index === 1) {
    color = 'blue';
} else if (index === 2) {
    color = 'green';
} // Add more cases as needed

// Optimize code by centralizing color assignment.
$('#btn_clear').css('background', color);

Answer №3

One approach worth considering is using the jQuery method .addClass() and .removeClass(), followed by defining the desired color for that class. By doing so, you can maintain a clear separation between application logic and styling concerns.

Styling

.blue-text {
  color: blue;
}

jQuery Script

var index = $("li").index( $(this).parent() );

if ( index === 1 ) {
  $('btn_clear').addClass('blue-text');
} else if ( index === 2 ) {
  $('btn_clear').removeClass('blue-text');
}

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

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...

The accumulation of MVC 3 Ajax requests is becoming overwhelming

I'm currently working on the following code snippet: $('.defaultLink').click(function () { $.ajaxSetup({ cache: false }); cleardiv(); $('#mainContent').empty() $('#mainContent').load(this. ...

Content within iframe is failing to load correctly on both Firefox and Internet Explorer browsers

On my website, I have 4 iframes embedded in 4 different tabs. I've noticed that the content is being cropped when viewed on Firefox, but it loads properly when using Chrome. Strangely, if I manually reload the iframe, the content displays correctly. T ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Guide to implementing hapi-auth-jwt2 authorization on a specific route within hapi.js?

I am facing an issue with using an access token in hapi.js. I am struggling to comprehend how to utilize this token for authentication purposes. Currently, I am referring to the article on dwyl/hapi-auth-jwt2. My database setup involves mongodb. However, I ...

Submitting a Django form using AJAX technology

Here is my implementation of the new_registration view : def handle_registration_request(request): context = {} if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): language = Language.objects.get(key="EN ...

Ways to merge multiple cells horizontally in a table right from the beginning

Is there a way to start the colspan from the second column (Name)? See image below for reference: https://i.stack.imgur.com/RvX92.png <table width="100%"> <thead style="background-color: lightgray;"> <tr> <td style="width ...

Validate Bootstrap - Transmit data from all form fields to external PHP script

Is there a way to send all input field values to a remote PHP file using Bootstrap Validator? In my log in form, I have two input fields. I'm utilizing Bootstrap Validator's remote validation on both of them. However, each validation only sends ...

Using the POST method in Node.js is not functioning properly on the Replit server when using express

Recently diving into the world of backend development, I have been utilizing Node.js on a Replit server with express to host an application for handling files: However, hitting a roadblock when attempting to execute a post request! var express = ...

"Exploring the method of adding information to a table with the help of

Here is the structure of my HTML table: <table id="tableOrderDetail" class="table-striped table-bordered" style="align: center; width: 100%;"> <thead> <tr> <th width="5%">Sr. No.</th> <th width="25%">Product N ...

Execute React program within VM Azure

After setting up my React application on Azure's virtual machine, I encountered an issue. When trying to access the public URL (DNS) of the VM, I received a "site can't be reached" message. This is the process I followed to launch my project on ...

Utilizing the hcSticky plugin for creating a scrolling effect on webpage content

I'm attempting to utilize the JQuery plugin, hcSticky, in order to achieve a scrolling effect on my fixed content. However, I seem to be encountering some difficulty getting it to function properly. What could I possibly be doing incorrectly? JSFIDDL ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

Using the set() method in Firestore with the merge option does not function properly when implemented in Node.js

const user = {name : myUsername}; databaseRef.set(user, { merge: true }); An error is occurring which states: Invalid use of type "undefined" as a Firestore argument. Despite following the Firebase documentation here, and seeing others use it in online ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

Submitting data using Angular's POST method

Disclaimer: As a front-end developer, my experience with servers is limited. I am currently working on an Angular 1.2 app that makes API calls to a different subdomain. The backend developer on the project has configured nginx to allow cross-domain reques ...

The app is not showing the Post Request message after it has been sent from the UI front end

I am currently developing a chat application using node.js, express.js, socket.io, and mongodb. However, I have encountered an issue during the Node.js and express.js implementation (socket.io and mongodb are not yet utilized). The problem is that the code ...

Invalid Jquery syntax: Anticipated an assignment or function call but encountered an expression instead

Here's a simple code snippet: _create: function () { var self = this; $("#Grid").on("click", ".Row", function () { $(self).hasClass('Expanded') && $('html, body').animate({ ...