Steps to update the border color to red when a button is clicked

I have an interesting question regarding validation and forms. I decided to use my own class, but I noticed that when the button is clicked, the border color does not display anymore.

I tried testing with CSS for invalid entries, and it worked. Now, I want the select border to turn red if the user presses the button and the entry is invalid. How can I achieve this? Here is my code:

var myForm = document.getElementsByClassName('needs-validation');
var btn = document.querySelector("[type='submit']")
btn.addEventListener("click", function() {
  if (myForm.checkValidity()) {
    ('.select-user-role').setCustomValidity('')
  } else {
    alert("no");
  }
});


// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
    'use strict';
    window.addEventListener('load', function() {
      var forms = document.getElementsByClassName('needs-validation');
      var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {
          if (form.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
          }
          form.classList.add('was-validated');


        }, false);
      });
    }, false);
.select-user-role:invalid {
  border-color: red;
}
<div class="form-group row">
  <label for="validationRole" class="col-form-label role">*Role:</label>
  <div class="col-3 ">
    <select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
      <option class="selectrole" selected disabled value="">Select ....</option>
    </select>
    <div style="margin-left: 10px;" class="invalid-feedback">
      Enter a valid user role!
    </div>
  </div>
</div>

<button type="submit" class="btn-primary submitbutton">Add</button>

This is how my website looks when there is an invalid entry: https://i.sstatic.net/YHFkt.png

I want the validation message and the border color to appear in red.

Answer №1

If you are looking to enhance user experience by dynamically adding a class to the select tag using JavaScript, here is a simple solution.

Give this script a try:

const myForm = document.getElementsByClassName('needs-validation');
const btn = document.querySelector("[type='submit']");
const box = document.getElementsByClassName('select-user-role');

btn.addEventListener("click", function() {
  if (myForm.checkValidity()) {
    box.classList.remove("error");
    ('.select-user-role').setCustomValidity('');
  } else {
    box.classList.add("error");
    alert("Invalid selection.");
  }
});

To style the error state in CSS, include the following:

.select-user-role.error {
  border-color: red;
}

This implementation also includes functionality to remove the red border when the selected user becomes valid.

Answer №2

It seems like the checkValidity function is missing, so I have created a temporary solution for now.

Whenever the button is clicked, if the validity is set to false, then the user-role element will be assigned the invalid class; otherwise, it will be removed.

var myForm = document.getElementsByClassName('needs-validation');
var btn = document.querySelector("[type='submit']");
var userrole = document.querySelector('.select-user-role');

const checkValidity = () => {
  //your code
  return false;
}

btn.onclick = () => {
  if (checkValidity()) {
    userrole.classList.remove('invalid');
  } else {
    userrole.classList.add('invalid');
  }
}
.select-user-role.invalid {
  border-color: red;
}
<div class="form-group row">
  <label for="validationRole" class="col-form-label role">*Role:</label>
  <div class="col-3 ">
    <select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
      <option class="selectrole" selected disabled value="">Select ....</option>
    </select>
    <div style="margin-left: 10px;" class="invalid-feedback">
      Enter a valid user role!
    </div>
  </div>
</div>

<button type="submit" class="btn-primary submitbutton">Add</button>

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

Using JavaScript to replace strings with values from an array in a Node Array

I have used custom JavaScript in GTM to create an array that needs some manipulation before generating a final value. Here are the initial values in my array: Array = [ [AED1,299.00], [AED2,699.00] ] My goal is to remove "AED" and commas from the values ...

Dynamic Express Route Handler

I have an array: var arr = ["/index.html", "/alternative_index.html", "/index"] and I am trying to make the Express server return the same output for these different routes: localhost:8080/index.html localhost:8080/alternative_index.html localhost:8080/ ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

Plotly: maintaining consistent color scheme across identical elements in multiple graphs

I am currently utilizing Plotly in Javascript to generate some interactive graphs. My goal is to create 2 pie charts that display the distribution of a sale based on A) units and B) value. While I am able to generate the plots successfully, I have notice ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

Changing the meta viewport tag

Trying to adjust the meta viewport tag based on the visual viewport width. I understand the process, but it's not functioning correctly. It seems like the JavaScript code might be executing too late for changes to apply effectively. While uncertain, t ...

Incorporating Google Analytics into a personalized Order Confirmation page on Woocommerce 3

I have a personalized gratitude page for post-checkout in WooCommerce where I want to include order details in a Google ecommerce tracking tag to log the sale in analytics. Part of this involves adding the following information for each item in the order.. ...

I am having trouble importing Material UI icons. Can anyone guide me on how to successfully use Material UI icons without any

While working on my project with React and Material UI, I encountered some difficulties when trying to import the material icons. I followed the code examples from the Material UI documentation, using version "material-ui": "^1.0.0-beta.41" and "material-u ...

Video tag with centered image

For a current project, I am in need of rendering a centered image (a play button) at runtime on top of a video based on the UserAgent. If the userAgent is not Firefox, I want to display the image as Firefox has its own playEvent and button on top of the vi ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

Enable JSON Data Management through Express

I am utilizing the lowDB dependency to manage JSON data in conjunction with Express, and for the most part, it is functioning properly. However, I have encountered a bug that I am struggling to resolve. I have created a /create page where users can input ...

Attempting to divide the given web address

Is there a way to divide the URL below into components and extract only "store" from it? http://www.store.com/products.aspx/Books/The-happy-donkey If so, what would be the best method to achieve this? ...

Show various shapes based on the values retrieved from MYSQL database

I am just starting to learn MYSQL and PHP, and I am currently working on creating a Course registration application using xampp. This application is designed to collect user data and store it in a MYSQL database. Within my MYSQL table, I have user details ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

Making a form select element responsive within a bootstrap 4 card component

Check out the code snippet I have here: This is how I envisioned it to look, and it works perfectly at large resolutions. However, when I scale it down to tablet size, the resizing of the select element doesn't seem to work properly. Here's a s ...

What could be causing the gap between the top row and the navbar when using Bootstrap 4?

I'm struggling to identify the source of a space or gap in my header section called #contact-stripe that separates it from the navbar. Despite checking for padding or margin settings, I couldn't pinpoint the issue. For better visibility, I' ...