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

A possible substitute for the "background-size" CSS attribute

After struggling for days without success, I find myself once again seeking your help. The current issue revolves around the slideshow on THIS website, which is powered by the jQuery Infinite Carousel Plugin. Despite adding background-size: auto 100%; to ...

Employ jQuery to send data to a php script

I am currently developing a search engine and I am trying to send data from jQuery to PHP. Below is the jQuery code I am using: <script> $(document).keypress(function(e) { if(e.which == 13 && $('#textfield').val()) { $ ...

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

How can I access multiple icons using jQuery?

Below is the JavaScript code I am using: $(document).ready(function() { $.getJSON("Stations.php", function(jsonData){ $.each(jsonData, function(key,value) { $('#selectStation') .append($("<option></option>") ...

The hover selector in Material UI and React is not functioning as expected

My code is experiencing an issue where the hover selector does not appear to be working. Although all other styling aspects function correctly, the hover effect is not visible. import React from "react"; import Paper from '@material-ui/core/Paper&apo ...

Utilizing jQuery to target a specific element by its ID within a function parameter

I am trying to work with this function: function doSomething(elementID) { $("div").append("<p id='"+ elementID +"'> A paragraph</p>"); /* It seems that the current approach is incorrect as it uses a selector with th ...

I'm noticing that my style.css changes are only showing up after a hard refresh, but then they revert back to an older version when I refresh normally

Apologies for the lengthy title. Here's the issue: I have a WordPress website with a custom theme and its corresponding child theme. Previously, updating the style.css file of the child theme would show the changes immediately after a website refresh ...

JQuery Ajax: Issue with updating Total Likes for posts when Like button is clicked

There are two JQuery Ajax calls in this scenario. The first call retrieves user messages from MySQL, along with the number of likes for each message and a button for users to like the message. This initial request is functioning correctly. The second Ajax ...

Loop through the list items in jQuery to display the total number of items

I am looking to display the total number of list items within each sublist item in my code. You can view it here: http://jsfiddle.net/NykJe/ <ul> <li>linkA</li> <li>linkB<span class="total"></span> <u ...

Is it possible to select an input field while using jQuery animate?

This query arises indirectly from a previous question regarding an animation script for a form. The script in question is a basic jQuery function that expands the width of an input field when it is focused on and reverts to its original width when unfocus ...

Is there a way to only load an external script once during a specific event on a webpage that uses all ajax?

I'm working with a basic webpage where all the links are ajax-loaded. Is there a way to load an external script only once when a link is clicked, to ensure optimal performance? ...

Video not visible in program (CSS, EXPRESS)

I am struggling to add a video to my page. The default method of creating a path for it isn't working for me. I believe I need to place the path somewhere else, but I'm not sure where. I have attempted to include the video in the same folder as ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

Is there a way for me to determine if a user has engaged with a form?

I'm surprised by how difficult it was to find information on this topic through Google. Currently, my struggle lies in wanting my form fields to change color based on validity only after the user has interacted with the form. I don't want invali ...

Tips on extracting the value from the chosen option in 2 separate rows with identical IDs

While looping through my table, each row is identified by the id="batchNo". I am trying to retrieve the selected value of each select option in every row. Although I attempted to achieve this with the provided code snippet, it only retrieves the selected ...

Adjust transparency in Bootstrap slider with picture indicator

Currently, I am in the process of creating an HTML page featuring a Bootstrap carousel. To enhance user interaction, I have replaced the standard selector with images that, when clicked, will transition the slider to display corresponding content. In orde ...

Utilizing Hyperlinks in jQuery DataTables Cell with Data Pulled from Mysql Table

I have a question that builds upon the one before it: How to display a hyperlink in a cell with jQuery DataTables There is also a Fiddle link provided My current query revolves around implementing hyperlinks when fetching data from a MySQL database table ...

Site Having Trouble Displaying Image

I'm currently working on a Bridgetown website using Bootstrap 5, and I've encountered an issue with adding an image that won't show up on the site. This is what it currently looks like: https://i.sstatic.net/IUR7x.jpg Code <nav class=&quo ...

What could be causing the lack of functionality for my button click in my JavaScript and HTML setup?

Currently, I am attempting to implement a functionality where I have two buttons at the top of my page. One button displays "French" by default, and when I click on the "English" button, it should replace the text with "French" using show and hide methods. ...