Unable to modify input box border

After setting up validation on a form and looking into previous answers, I have come across the following solution:

CSS

.required_field {
    border-style: solid;
    border-color: red;
}

Whenever a field is empty or null, I am adding the class:

JavaScript

$('#new_name').addClass('required_field');

I have tested this class on a div and it adds the border correctly. However, when applied to an input box, it does not change the border color.

HTML

<form>
    <input type="text" id="new_name" name="new_name">
    <input type="submit">
</form>

While the class is being added, the border color of the input box remains unchanged. What could be causing this issue?

ANSWER

The problem was that the input element already had existing CSS rules affecting its appearance, preventing the new class from taking effect as expected.

By adding !important at the end of each rule in the required_field class (as suggested in the comments), the override forced the border color to change as intended.

Answer ā„–1

When wrapped in $(function() { .. }) and preventDefault, it works as expected:

Check out the test here: https://jsfiddle.net/mplungjan/akavrx6y/ since SO does not allow submissions

$(function() {
  $("form").on("submit", function(e) {
    if ($.trim($('#new_name').val()) == "") {
      e.preventDefault();
      $('#new_name').addClass('required_field');
    } else {
      $('#new_name').removeClass('required_field');
    }
  });
});
.required_field {
  border-style: solid;
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="new_name" name="new_name">
  <input type="submit">
</form>

The add/remove functionality can also be achieved using:

$('#new_name').toggleClass('required_field', $.trim($('#new_name').val()) == "");

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

Information extracted from the database without considering any line breaks

When data is stored in my MySQL database, the line breaks of the text input are preserved. However, when retrieving the data, the line breaks disappear and everything is displayed as one continuous string without any <br> tags. Any insights into why ...

How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code: html, body { margin: 0px; padding: 0px; } bo ...

Struggling to target specific elements in CSS that are dynamically generated through JavaScript

After using JavaScript to generate some divs, I ended up with the following code: const container = document.querySelector('#container'); for(let i = 1; i < 17; i++) { var row = document.createElement('div'); row.id = 'r ...

Tips for sharing information through a JSON array

"advertisement_types":["ATM","Banner/Poster","Stalls"] Here is the HTML code: input(type='checkbox', value='Mobile/Communication Tower', ng-model='advertisement_types') | Mobile/Communication Tower ...

Is it possible to locate an element using regex in Python while using Selenium?

Is it possible to interact with a dynamically generated dropdown list using Selenium if I only know the phrase present in its id or class name? Can Selenium locate an element using regex and click on it accordingly? ...

Transform a Div element into an image, ensuring compatibility with Internet Explorer 7 and 8

Currently, I am utilizing the jqplot charting library to create charts in my ASP.NET MVC application. Within a div element, the chart is being rendered. The goal is to convert this div element into an image and export it to a PDF document. The jqplotToIm ...

Alignment of the button in a vertical position

Hey there! I've got a button set up with Bootstrap for centering, but now I'm looking to vertically align it in the middle of the page without any margin or padding. Any ideas on how to go about doing that? Here's the HTML code: <div cl ...

Using Three.js to display a CSS3D-rendered DIV in full-screen mode

After extensively experimenting with the three.js library, I was able to establish two distinct scenes ā€“ one canvas-rendered and the other css3d-rendered ā€“ both displayed using the same perspective camera. Note: Despite my efforts, I am constrained to ...

Eliminating elements that adjust according to different screen sizes

Website: I am currently working on customizing a Tumblr theme I downloaded by removing some responsive elements. The rollover effects I created are being affected when the screen size goes below 1024px, and I am not happy with how it looks. Additionally, ...

Can you advise on how to generate a key to access an environment.ts value within a *ngFor loop? Specifically, I am trying to locate keys that follow the pattern 'environment.{{region}}_couche_url' within the loop

I currently have a block of HTML code that is repeated multiple times. <!-- Metropolitan Map --> <div> <app-map [name] = "(( environment.metropole_name ))" [layer_url] = "(( environment.metropole_layer_url ))" ...

Ways to prevent html header content from being incorporated in jquery post outcomes

I've implemented jquery's "$.post()" function to insert a new list entry into the mysql database using php. $(document).ready(function(){ $(".theSubmit").click(function(){ var content = $("textarea").val(); var listn = $("in ...

Issue with horizontal navigation in CSS

I'm struggling with styling my CSS navigation bar. The last list item is moving to a second line, which really messes up the look of my website. Can someone take a look at my code and point out what I'm doing wrong? Thank you in advance. HTML: ...

Is it possible to utilize ::before content in order to turn a div into a clickable link?

I am currently working on customizing the appearance of a Wordpress site, and I have encountered an issue with a specific DIV element that I would like to make clickable instead of using its current content. The page-builder being used on the site is makin ...

Unable to modify the background color using the .css stylesheet

https://i.sstatic.net/uKcMs.jpgMy attempts to change the background color in a simple HTML page using a CSS style sheet have been unsuccessful. Despite no errors being present in my code, I am encountering this strange issue. <!DOCTYPE html> < ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: https://i.sstatic.net/Wa4mo.jpg with this new link: https://i.sstatic.net/hqVuQ.jpg without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restrictio ...

How can the HTML email width be adjusted on Outlook 2016?

When I send out HTML emails, I encounter an issue where the content takes up the full width no matter what. I have tried adjusting the width of table, tr, td, div, and body elements, but it still persists. This problem occurs on Outlook 2016 across all W ...

Learn how to quickly resolve the issue in nodejs where the new image automatically replaces the old one when added

I have successfully created a file to upload images, however the image name appears as undefined.jpg in this project. I am using the Express file upload middleware. *admin.js var express = require("express"); const productHelpers = require("../helpers/pr ...

When a div element is clicked, it becomes the selected element and borders are displayed around it

Within a div on my wordpress site, the logo is prominently displayed. Feel free to check it out here: Strange issue - whenever I click on the logo, a large rectangular box suddenly appears. I've experimented with the outline and user-select properti ...

What is the best way to trigger one of two different functions randomly when an HTML button is clicked?

Is there a way to have an HTML button trigger one of two functions randomly on click event? Iā€™m utilizing PHP on the server side and jQuery on the client side. I've tried using the following code but nothing happens when I click the button image... ...

One Background Image Serving Multiple Divs

Can you use one image (PNG or SVG) as the background for multiple divs? Take a look at the images below to see how it could work. And if the screen width gets smaller and the divs stack up vertically, is there a way to change the background accordingly? D ...