The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red after an incorrect input? Is there a bootstrap class available that automatically changes the borders to red after wrong input?

if ($('#TextBoxID').val() == '') {
  $('#TextBoxID').css('border-color', 'red');
} else {
  $('#TextBoxID').css('border-color', ''); 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css">
    
    <div class="sign-up container">
        <h2>Sign Up</h2>
        <p>Please fill out this form to create an account.</p>
        <form action="" method="post">
            <div class="form-group">
                <label>Username</label>
                <input id="TextBoxID" type="text" name="username" class="form-control" value="">
                <span class=" text-danger"></span>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" value="">
                <span class="text-danger"></span>
            </div>
            <div class="form-group">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" class="form-control" value="">
                <span class=" text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">
            </div>
            <p>Already have an account? <a href="#">Login here</a>.</p>
        </form>
      </div>
      
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a3bca3a3b6a1fdb9a093e2fde2e5fde2">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7J42ftXTSDUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

Answer №1

The issue lies with the textbox consistently displaying in red color.

This problem is caused by the line if ($('#TextBoxID').val() == ''). Make sure to validate this on form submission

function validateForm(e) {
  e.preventDefault();
  if ($('#TextBoxID').val() == '') {
    $('#TextBoxID').css('border-color', 'red');
  } else {
    $('#TextBoxID').css('border-color', '');
  }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200;400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css">

<div class="sign-up container">
  <h2>Sign Up</h2>
  <p>Please complete this form to register an account.</p>
  <form action="" method="post">
    <div class="form-group">
      <label>Username</label>
      <input id="TextBoxID" type="text" name="username" class="form-control" value="">
      <span class=" text-danger"></span>
    </div>
    <div class="form-group">
      <label>Password</label>
      <input type="password" name="password" class="form-control" value="">
      <span class="text-danger"></span>
    </div>
    <div class="form-group">
      <label>Confirm Password</label>
      <input type="password" name="confirm_password" class="form-control" value="">
      <span class=" text-danger"></span>
    </div>
    <div class="form-group">
      <button onclick="validateForm(event)" type="submit" class="btn btn-primary">Submit</button>
      <button type="reset" class="btn btn-default" value="Reset"></button>
    </div>
    <p>Already a member? <a href="#">Log in here</a>.</p>
  </form>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

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

Steps for achieving uniform positioning of a div element that dynamically appears within a table with two rows and four table data cells

If I want to display the same div in different positions dynamically on my page, how can I achieve that? My page has a table with two rows and two columns, each containing an Embed button. When these buttons are clicked, a div is shown with a list of site ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Reactstrap and React-router v4 are failing to redirect when there is a partial change in the address link

Within the header of my website, <NavItem> <NavLink tag={Link} to="/template/editor">Create New Template</NavLink> </NavItem> On the routing page of my website, <BrowserRouter> <div className="container-fluid"> ...

Encountering the error "Error: Maximum update depth exceeded" while coding a React private Route with infinite

Attempting to render components inside private routes only if the user is authenticated, but encountering an error message that reads: "Error: Maximum update depth exceeded." This issue typically arises when a component continuously calls setState within c ...

Struggling to pass along the URL value from a promise to various modules within Express is proving to be quite a challenge for me

I've been working on an app using ngrok, following a guide from Phil on setting up ngrok with nodemon. You can find the link to the post here. I need to have access to the URL received from the promise in the bin folder throughout the app server so t ...

Using div tags may cause rendering issues

I am trying to use multiple div tags with webkit borders, but for some reason only the one called 'Wrapper' is displaying properly. Here is my code: .wrapper { margin: 20px auto 20px auto; width: 800px; background: url('images/background_1. ...

Having difficulty modifying the styling of a paragraph within a div container

I have been working on a function that is supposed to adjust the font-size and text-align properties of a paragraph located within a div tag once a button is pressed. function customizeText() { document.getElementById('centretext').innerHTML = ...

Discover the exact location of an HTML element within an iframe

I am currently attempting to determine the position of an element that is within an iframe. I have written the following code for this purpose: // Custom function to calculate the position of an element on the page function getElementPosition(elem){ var ...

JavaScript allows users to input an array name themselves

When fetching rows from my database using AJAX, I transform them into an array with a variable identifier. Here is the PHP code: $query_val = $_GET["val"]; $result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%&apos ...

Importing a library dynamically in Next.js

I'm currently facing a challenge in dynamically importing a library into one of my next.js projects. The issue arises when I don't receive the default export from the library as expected. Initially, I attempted to import it the next.js way: impo ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...

In my attempt to simulate redis using jest and javascript, I've noticed that whenever I try to access redis.mock.instance[0], it consistently returns as empty

I'm currently attempting to simulate redis with jest and JavaScript, but I'm encountering an issue where accessing redis.mock.instance[0] always returns empty. RedisWrapper.js: const Redis = require('ioredis'); const REDIS_USER_TTL = 6 ...

Guidelines for validating email input using jQuery

Although I am not utilizing the form tag, you can still achieve form functionality using jQuery Ajax. <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password ...

Having trouble with Vue 3 Composition API's Provide/Inject feature in Single File Components?

I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the follo ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

"Encountered a Http502 error while running the Node component (code provided for reference purposes

Encountering the Http502 error while developing a node component for chatbot. The first code snippet works flawlessly, but the second one triggers an Http502 error. Both snippets share the same host and proxy settings, with only the endpoint being differen ...

An inquiry regarding props in JavaScript with ReactJS

Check out the following code snippet from App.js: import React from 'react' import Member from './Member' function App () { const members = [ { name: 'Andy', age: 22 }, { name: 'Bruce', age: 33 }, { n ...

Encountering a glitch when integrating Bootstrap 4 with Rails 6 Webpacker

My Rails 6 application is set up with jQuery in the following configuration: config/webpack/environment.js : const { environment } = require('@rails/webpacker'); const webpack = require('webpack'); environment.plugins.append('P ...

Dealing with Buffer data received from a NextJS backend API

In my NextJS application, one of the backend API routes returns a JSON object that includes a buffer. // The nodeConfiguration contains a buffer for the nodeId property res.status(200).json(nodeConfiguration); However, when trying to display the nodeId va ...