How to update an HTML class using JavaScript with conditional statements

I've successfully implemented a bootstrap validation form that changes the inputField color based on error and success states.

However, I'm facing an issue with changing the text-color and border-color of the Label element. I've tried various JavaScript solutions but none seem to work for me as I'm not well-versed in javascript.

HTML

<form action="" class="form-horizontal form-bordered storyForm" novalidate>

<div class="form-body">
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="email">Email</label>
            <input type="email" id="email" class="form-control" name="email" required data-validation-required-message="This field is required">
        </div>
    </div>
    <div class="form-group" id="form-group">
        <div class="controls">
            <label class="control-label" id="label" for="password">Password</label>
            <input type="password" id="password" class="form-control" name="password" required data-validation-required-message="This field is required">
        </div>
    </div>
</div>;

<div class="form-actions">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="offset-sm-3 col-md-9">
                    <button type="submit" id="submit" class="btn btn-success"> <i class="fa fa-check"></i> Submit</button>
                    <button type="button" class="btn btn-inverse">Cancel</button>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

form.storyForm label{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #000;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid rgba(0,0,0,.15);
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.error{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #ef5350;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #ef5350;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}
form.storyForm label.validate{
  padding: 0px 25px;
  /* background-color: rgba(0,0,0,.15); */
  color: #26dad2;
  border-radius: 4px 4px 0px 0px;
  border: 1px solid #26dad2;
  border-bottom: 1px solid white !important;
  top: 1px;
  position: relative;
}

The JavaScript code snippet I'm using to toggle classes

<script>
$(document).ready(function() {
    $("#submit").click(function() {
        if ($("#form-group").hasClass("error")) {
            $("#label").addClass("error");
        } else if ($("#form-group").hasClass("validate")) {
            $("#label").removeClass("error");
            $("#label").addClass("validate");
        }
    });
});
</script>

I have also attempted using class selectors without success

<script>
$(document).ready(function() {
 $("#submit").click(function() {
    if ($(".form-group").hasClass("error")) {
        $(".control-label").addClass("error");
    } else if ($("#form-group").hasClass("validate")) {
        $(".control-label").removeClass("error");
        $(".control-label").addClass("validate");
    }
 });
});
</script>

Answer №1

Make sure that when using the dollar sign ('$') in your JavaScript code, you have included the JQuery library. In JQuery, '$' serves as the primary base object or function. If you are not utilizing JQuery, consider using native JavaScript methods like .getElementById() or .querySelector() and pass your id value accordingly.

Additionally, opting for querySelector is a more effective approach to tackle this functionality.

For further guidance, you can refer to the MDN getElementById() documentation and MDN querySelector() documentation.

I trust this information proves beneficial! Best of luck with your coding endeavors!

Answer №2

When working in JavaScript, ID selectors will only return the FIRST element with a matching ID on the page. If you need help understanding how this works, check out this simple codepen example: https://codepen.io/anon/pen/bYoqZP

It's important not to use an ID selector for your sizzle selectors. Instead of $('#xxxxxxx'), consider using either an element selector like $('label') or selecting by class like $('.control-label'). In your code, using an ID selector for form-group will also cause issues as it will only target the first element with that ID, potentially affecting the functionality of multiple form groups.

In the provided sample, there isn't any indication of how form validation is being handled or how error classes are applied. Currently, the submit button is set up to submit the form and adjust classes, but without proper form processing code, this won't have any significant impact. Adding an error class to form groups and submitting the form would demonstrate the effects of the changes, but more comprehensive code is needed to properly handle form data submission and manipulation.

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

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

An interactive data organizing tool on a website

Similar Question: Is there a Spreadsheet-like control for web applications? I am exploring different tools available, unsure of how to implement what I have in mind. Currently, my webpage uses javascript to parse user-provided information. Users copy ...

The this.setState method does not seem to be properly updating the nested array within the user object. However, when checking the same logic using console.log, the object

When the user selects multiple meals, they are stored in an array of objects inside the user object. Upon clicking submit, the code utilizes setState to update the user's meals as follows: submitAllMeals(arrayOfMeals) { this.setState({ u ...

Steady Content of a Parallax Webpage

Hey there! I recently put together this awesome site and I'm facing a challenge with fixing text on the first slide, specifically the one featuring the Nike basketball. Right now, the text 'The first of its kind' is part of the background im ...

Necessitating the selection of at least one option only when another condition is met

Struggling to figure out this validation schema using Yup for the first time. Essentially, I need to ensure that if hasCategory is set to true, at least one category must be selected. Currently, my schema looks like this: const validationSchema = Yup.objec ...

Verify whether the array containing objects includes a specific object

I'm currently attempting to determine whether an array of objects contains a specific object. I would like the function to return true if there is an object in the array that has identical values, regardless of the object id. Here's how I initial ...

Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't becom ...

The page is not responding after closing the modal dialog

My web application is built using Spring Boot for the backend and Thymeleaf for the front end. The app displays all available groups for users to review. When a user clicks on a group, the documents within that group are listed in a tabular form. Clicking ...

Gathering information from a website where the URL remains constant even after clicking on a specific button

Visit this website for bus tickets: I am working on scraping data related to bus trips from the mentioned site. However, the data I need to scrape depends on the user-selected date in my web application. Does anyone have suggestions on how I can develop ...

Tips for boosting the tabindex in a React search result list with ul-li elements

Implementing search results using ul li: <ul className="search-result"> <li tabindex="1">title here...</li> <li tabindex="2">title here...</li> <li tabindex="3">title here... ...

Leveraging RouteProvider in Angular

I've encountered an issue while working with route provider. I'm trying to access a different path on my localhost:8080/showThemes.html page using the following method: <a ng-href="#/category/{{themes.theme}}"> <img class="imgCenter" ...

Tips for automatically closing all other divs when one is opened

I have multiple divs structured like this: <div id="income"> <h5 onclick="toggle_visibility('incometoggle');">INCOME</h5> <div id="incometoggle"> <h6>Income Total</h6> </div> </div> <d ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Adding a PHP file into an HTML page using JavaScript include

Recently, I was assigned to collaborate with a third-party vendor who displays movie times on their platform. We were given the opportunity to co-brand our website on their platform by creating a wrapper for our site. This wrapper would allow the movie tim ...

Unable to access the property '__reactAutoBindMap' as it is undefined

I've been struggling with setting up server side rendering with React for the past week. It's a new project using an express server and I'm trying to render a simple hello world react app that utilizes react-router-component. To get some he ...

Determining the Maximum Number of Characters Allowed in a Div Using jQuery

Could anyone provide guidance on how to populate a div with single characters? I want the div to span the width of the viewport. The code to get the width is: $(window).width(); I would like JavaScript to generate HTML similar to this: <div id="text ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

A stationary webpage nested within a lively pathway on NuxtJS

I have a Nuxt app with a list of cars available at: /cars. You can select a specific car at /cars/:id. I would like to have a toolbar that routes to different views such as: /cars/:id/routes, /cars/:id/drivers, etc. Within the /cars/:id page, I have creat ...

Choose the correct checkbox among several options

On my webpage, I am facing an issue with checkboxes. No matter which checkbox I click on, only the first one is getting checked. I can't figure out what the problem is. Initially, the checkboxes weren't showing as checked, but now only the first ...

"Mastering the art of data retrieval in ReactJS: A guide to utilizing hooks in functional

I'm in the process of working with nextjs and I'm attempting to implement a "functional component" utilizing "hooks" for fetching data using "axios". However, I'm encountering the following error message: "AxiosError: Request failed with sta ...