Is there a way to dynamically change select2 styling using code when a form is submitted?

Having trouble highlighting empty select2 selects when a form is submitted? I'm struggling to override my existing CSS styling upon document load.

Check out my jQuery attempt:

var $requiredUnfilledItems = $(".required:not(.filled)");
if ($requiredUnfilledItems.length > 0) {
  $requiredUnfilledItems.each( function(){
    $(this).addClass('warning-border');
  });
}

Here's the CSS for .warning-border:

.warning-border { 
    outline: none !important;
    border-color: red !important;
    box-shadow: 0 0 10px red !important;
}

It's supposed to override this:

.select2-container--default .select2-selection--single {
    width: 100%;
    padding-left: 4px;
    height: 100%;
    border: thin solid lightgray;
    height: 30px;
}

But it's not working. I've also attempted this, which may just show that I still have some CSS learning to do:

.warning-border, .select2-container.warning-border { 
    outline: none !important;
    border-color: red !important;
    box-shadow: 0 0 10px red !important;
}

Any help would be greatly appreciated!

Answer №1

It's best to avoid using !important in your CSS and instead understand how cascading works. There are plenty of helpful resources online that can explain this concept better than I can--

https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

In the example code snippet provided, a JQuery handler has been implemented so that a text input field detects when it is filled and adds or removes a "filled" class accordingly onkeyup event. Consider adding a similar handler if one is not already present in your codebase (though chances are you might have one already).

The CSS has been modified to ensure that certain class combinations do not highlight in red (located at the bottom of the stylesheet in the snippet).

An adjustment was made from using border-color to shorthand properties in the CSS to guarantee consistency across affected properties. If there were any issues with how it functioned previously, this change should address them.

$( "input[type=text]" ).keyup(function() {
  if(this.value != '') $(this).addClass('filled');
  else
    $(this).removeClass('filled')
});

$("form").submit(function(){
  var $requiredUnfilledItems = $('.required:not(.filled)'); 
  if ($requiredUnfilledItems.length > 0) 
  {$requiredUnfilledItems.each( function(){$(this).addClass('warning-border');
   });
  }
  else { alert("You entered in " + this.name.value); }
  return false;})
.warning-border { 
    outline: none !important;
    border: thin solid red;
    box-shadow: 0 0 10px red;
}

.warning-border, .select2-container.warning-border { 
    outline: none !important;
    border: thin solid red;
    box-shadow: 0 0 10px red;
}

.warning-border.filled, .select2-container--default .select2-selection--single {
    width: 100%;
    padding-left: 4px;
    height: 100%;
    border: thin solid lightgray;
    height: 30px;
    box-shadow: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" onsubmit="">
<input id="name" type="text" class="required filled" value="Name"/>
<input type="submit">
</form>

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

Tips for centering the second content within a div block

<div style="height: 100%; background: red"> <div style="height: 100px; background: green"> </div> <div style="background: blue;"> <h1>Content</h1> </div> </di ...

Creating a spinning Cube with separate fields for x, y, and z rotation speeds: a step-by-step guide

After dabbling in Java, Visual Basic, HTML, and CSS, I'm now looking to create an interface featuring a central spinning cube with 3 fields to control its x, y, and z rotation speeds. Can you suggest which language would be the best fit for this proje ...

Require the capability to bypass inline CSS styling

Currently facing an issue with a wordpress website I am constructing using iThemes Builder. The problem arises when integrating the plugin Jquery Megamenu, as the drop-down menu gets truncated due to an overflow:hidden property that cannot be overridden i ...

A guide on looping through data in a JSON-serialized System.Data.DataTable with the help of jQuery

Here is an example of the JSON format: [ {"animal":"dog", "sound": "bark"}, {"animal":"cat", "sound": "meow"} ] I am looking to iterate over each record {...} within the brackets [ ], starting with the dog-record and then moving on to the cat- ...

Why is the CSS selector `:first-child:not(.ignore)` not working to exclude the `ignore` class from the selection?

Is there a way to utilize the first-child selector with the not(.ignore) selector to target every element that is the first child of its parent, except when that first child has the class ignore? I've experimented with :first-child:not(.ignore){...}, ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

How can I pass the dynamically generated ID from PHP to AJAX/jQuery using an anchor tag?

I'm seeking help with jQuery and Ajax as I am new to it. My issue is that I have multiple 'edit' buttons in a table, one for each row's data. When I click on an edit button to modify the data, they all open at once instead of just the s ...

Creating a horizontal layout for list items that are responsive using CSS

My website has a "Featured" section with 3 equally sized elements displayed horizontally. I want to make the webpage responsive by using percentage widths, but when I resize the window to less than the list width, the items stack on top of each other. Che ...

Personalizing the User Interface of Azure AD B2C using dynamic HTML

After customizing my own html and CSS for Azure AD B2C sign-up and sign-in policy using the steps outlined in this resource, I have successfully created custom Sign-Up and Sign-In pages. However, my next goal is to make the sign-up page dynamic by passing ...

Creating the perfect layout with CSS: A step-by-step guide

As I work on refining my layout to achieve the desired look, let me share my initial idea before delving into the issue at hand. Currently, I am attempting to create something similar to this: https://i.stack.imgur.com/rtXwm.png This is how it appears a ...

Having multiple HTML select elements and utilizing jQuery AJAX

I am looking to implement a dynamic multiple select using AJAX and jQuery. The first select (c1) is functioning correctly. When I click on it, it triggers the appearance of another select (c2). Similarly, clicking on the second select (c2) should lead to ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...

Customize the progress bar color in Bootstrap by setting a unique color to it

Is it possible to apply a custom color to the progress bar in Bootstrap that is not one of the standard options like success, info, warning or danger? I attempted adding the following code snippet to my bootstrap-theme.css file: .progress-bar-custom { b ...

The div is empty when trying to display Google Maps

When I set the height of my Google map div in pixels, it displays correctly. However, when I try to set it as a percentage, specifically 100%, the map does not show up. I have tried setting the height of all parent divs as well, based on suggestions from S ...

Sending empty parameter data via Ajax to an MVC controller

Initially, I had no issues passing a single parameter to my MVC Controller through Ajax. However, when I attempted to add an extra parameter, both parameters stopped sending data to the Controller. Can anyone help with this issue? Thank you! Ajax Code: ...

Utilizing Jquery and Ajax to create a dynamic dropdown selection feature based on dependencies from a JSON file

Could you assist with the code snippet below? I have a form where each dropdown list depends on the selection above it. Based on the user's selection, the appropriate data should display in the subsequent dropdown list. I am trying to make dropdown l ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

Angular 4 allows the addition of an image from right to left upon clicking

I've been working on angular 4 and I've successfully implemented the functionality of adding flags. However, the issue is that the flags are currently appearing from left to right. What I'm aiming for is to have the images appear from right ...

Is it possible to index elements starting from 1 in Jquery?

Is there a way to make the index element start from 1 without having to use "if(index ===0) return true;"? $( 'h3' ).each(function( index ) { ...do things... } Many loops typically begin at 0 because of their association with arrays, wh ...