Struggling with jquery's addClass method when trying to apply a class to

Below is a sample tr:

<tr>
  <td><input type="text" class="ingredient required" name="ingredient"></td>
  <td><input type="number" class="amount required" name="amount" ></td>
  <td><input type="number" class="carrier required" name="carrier" max="100"></td>
  <td><input type="number" class="kilo required" name="kilo"></td>
  <td><select class="tableDropDown" style="min-width: 100px;">
           <option value="other">The Manufacturer</option>
           <option value="me">Me</option>
      </select></td>
  <td><input class="packSize" type="number" disabled></td>
</tr>
<button type="submit" class="analyze">Analyze</button>

If the select value (.tableDropDown) is set to "me", I would like to add the class .required to .packSize, as it's used for form validation.

I have attempted to achieve this with jQuery and the addClass method, but so far it hasn't been successful. Here's what my code looks like:

 $(".tableDropDown").on('change', function () {
    var packSize = $(this).parents('.formulaRow').find('.packSize');
    if ($(this).val() === "me") {
        $(packSize).prop('disabled', false);
        $(packSize).addClass(".required");
    } else {
        $(packSize).prop('disabled', true);
        $(packSize).parents('td').removeClass("redClass");
    }
    if ($(this).val() === "me" && $(packSize).val() === "") {
        $(packSize).parents("td").addClass("redClass");
    }
});

The validation function being used is as follows:

$(".analyze").click(function() {
var counter = 0;
$(".required").each(function() {
    if ($(this).val() === "") {
        $(this).parents("td").addClass("redClass");
        counter++;
    }
});

    if (counter > 0){
        alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}

The CSS snippet redClass highlights the td in red to indicate errors after clicking submit.

This approach works for other cells, but for some reason, the addClass method isn't successfully adding the required class to .packSize. I'm currently troubleshooting this issue.

Answer №1

Avoid using ".required" in addClass, instead, it should be just "required".

Instead of this line:

$(packSize).addClass(".required");

You should use:

$(packSize).addClass("required");

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

Update Table Row Background Color in Separate Table by Clicking Button Using JQuery

Two tables are involved in this scenario - one that receives dynamically added rows, and another that stores the data to be included. The illustration above displays these tables. Upon clicking the Edit button, the information from the selected row in Tab ...

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? ...

Show me all the posts from the database in a single row

When attempting to display all the entries from my posts table in the database, I noticed that only one entry is showing up. If I try to duplicate the code, it simply repeats the same ID from the posts table. <div class="row"> <?php $query ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...

Tips for including a DOCTYPE declaration when generating an XML document with the "xmlbuilder" npm library

Is it possible to include a !DOCTYPE declaration in an XML file while using the 'xmlbuilder' package? I want to add something similar to the following: <!DOCTYPE IAD.IF.ESTATE.FORRENT SYSTEM "http://www.finn.no/dtd/IADIF-estateforrent71.dtd" ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

Display the item with jQuery once the CSS generated by jQuery has finished loading

Is it possible to delay the visibility of an object until my script finishes loading? I tried using ajaxcomplete() and ajaxSuccess() without success. Check out the code snippet below for an example. There's an image with the id: imagefocus. Whenever ...

Make sure to employ Bootstrap's justify-content-between and stack-to-horizontal col correctly

I am currently working on a responsive form that contains 1 label, 1 input field, and 5 buttons. Both the buttons and the input field are located under col-8. The positioning I aim for the buttons is as follows: They should start below and align with ...

Tips for implementing a boundary on a multipart/form-data request when utilizing the jquery ajax FormData() function for handling several files

I'm facing an issue with my HTML form that needs to upload 3 parts to an existing REST API in a single request. The problem lies in setting a boundary on a FormData submission and I haven't been able to find relevant documentation for it. I&apos ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Several buttons, each requiring to show distinct text

Currently, I am attempting to enhance an existing project that was graciously created for me. I must admit, I am quite new to this, so please be patient with me! In my project, there are 9 buttons, each triggering the display of a different image upon bei ...

Is there a way to switch the language on the date-picker tool?

My date-picker has a unique set up: <input type="text" ng-readonly="true" class="form-control" datepicker-popup="yyyy-MM-dd" ng-model="filter.FInicial" is-open="filter.controlFInicialAbierto" min-date="minDateIni" max-date="maxDat ...

What's the best way to align several buttons in the center of the screen horizontally?

I'm struggling to properly align divs with images inside another div. My goal is to insert buttons into my HTML and use jQuery to center them automatically, but I can't seem to get it right. You can view the fiddle I've created here: http:/ ...

Connecting to a pathway of Material-UI menu items

I am currently utilizing Material-UI's menu components as part of my project requirements. However, I am encountering difficulties in properly routing each MenuItem to an existing route within my application. As a temporary solution, I have resorted ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

I am trying to figure out how to style each box individually, but I'm running into some confusion. There are three different classes to choose from, with the child class

Struggling to style the ten boxes individually? Renaming each class of the box child didn't work as expected? Wondering how to select and style each box with a unique background color? Also facing issues with displaying the logo image on the navigatio ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...