Modifying CSS using jQuery can be achieved with the .parent().addClass method, however, using just .addClass

When I first started working on my validation using jquery/javascript, it was not very effective. However, with the implementation of a new css class and updates to my jquery validation, things have greatly improved.


I've been focusing on enhancing user input validation in different forms within a web portal based on the python web framework cherrypy, particularly through jquery. Initially, a single check was done for all inputs failing validation, turning borders and labels red. Now, individual checks are performed for each required field, with error messages showing only for fields that fail validation.

My next goal is to reset the css styles back to their defaults before conducting the validation check. This would prevent fields corrected by users from being marked with red borders and labels. Despite this, any fields still failing validation during submission will be highlighted in red again.

Is there a way to achieve this without multiple lines of code at the beginning of the submit function?

document.getElementById('elementHere').style.borderColor = "black";
document.getElementById('elementHere').style.color = "black";

$( document ).ready(function() {
  
  //snip

  $("#btnSubmit").click(function(){
        $("#dlgmessage").html("Processing...");
        $("#dialog-message").dialog("open");
        
        //New Validation
        var validated = "yes";
        var msg = "One or more fields do not meet the validation requirements:<ul>";
        
        //More jquery validations
        
       
      
        //Make sure basic inputs are filled in
        //if (
        //    Clean($("#txtIndex").val()) === "" ||
        //    Clean($("#txtSourcetype").val()) === "" ||
        //    Clean($("#txtUseCase").val()) === "" ||
            //more validation conditions
        //){
            //Error message display
            //console.log("Missing Required Fields");
            // return;
        //}
        
      
      
        //Successful validation
        var postdata = {
            record_id: Clean($("#txtID").val()),
            splunk_index: Clean($("#txtIndex").val()),
           
          
        } ;
       
      
        $.post( "/submit", {data:JSON.stringify(postdata)},
            function( data ) {
                var msg = data;
                                },
            'text'
        );
      
     
    });
});

I'm looking for a solution where the css can be reset automatically, but if specifying each element and its default color is necessary, that's also acceptable.


EDIT:

After reevaluating my previous code which was quite basic, I made significant improvements to make it more dynamic and avoid extensive if statements. The latest version seems promising, as classes are added to html elements, yet the styling changes like applying red color to invalid fields are missing. The earlier method with

$(field_id).parent().addClass("error");
worked for me initially, but now I want only failed fields to turn red.

Below is my updated code

Thank you

$( document ).ready(function() {  
  $("#btnSubmit").click(function(){
        $("#dlgmessage").html("Processing...");
        $("#dialog-message").dialog("open");

        var postdata = {
            splunk_host: Clean($("#txtSplunkHost").val()),
            ip: Clean($("#txtIP").val()),
           
        } ;

        
        //Validation process
      
      
        //---------------------------------------------------------------------------------------------------
     $("#dialog-message").dialog({
      modal: true,
      autoOpen: false,
      position: { my: "top", at: "top", of: $("#page-inner") },
      buttons: {
        Ok: function() {
          $( this ).dialog( "close" );
        }
      }
    });    
});
/*========================================
Errors
========================================*/
.error input {
  border: 2px solid red;
}
.error label {
  color: red;
}
<div class="form-group">
<label id="txtSplunkHost_label">Splunk Host (*)</label>
<input class="form-control" placeholder="Splunk Host" id="txtSplunkHost" value="" maxlength="255" autofocus="">
       
</div>
<button type="button" class="btn btn-default" id="btnSubmit">Submit</button>

Answer №1

Looking for a more efficient implementation? Here's a dynamic approach that eliminates the need for numerous if conditions and DOM selectors. This method follows the recommended css strategy instead of applying individual style properties.

The code is straightforward and easy to comprehend.

$("#submit").on("click", function(e) {

  //Prevent default form action
  e.preventDefault();

  //Add all inputs into an array
  var inputs = [$("#name"), $("#address")],
    is_form_valid = true;

  //Validations
  for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].val() == "") {
      inputs[i].parent().addClass("error");
      inputs[i].focus();
      is_form_valid = false;
      break;
    } else {
      inputs[i].parent().removeClass("error");
    }
  }

  //Form has no validation errors.
  if (is_form_valid) {
    //Do your work here...
    alert("Form submitted");
  }

});
.error input[type="text"] {
  border: 2px solid red;
}

.error label {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form novalidate>

  <div class="field">
    <label for="name">Name:</label>
    <input type="text" id="name">
  </div>

  <div class="field">
    <label for="address">Address:</label>
    <input type="text" id="address">
  </div>

  <button id="submit" type="submit">Submit</button>

</form>

UPDATE

It seems you have made some improvements to enhance readability :) While there are various form validation libraries available, I recommend utilizing them without reinventing the wheel. Nonetheless, this exercise serves as good practice in understanding coding standards.

Your issue lies in incorrect placement of css classes within your HTML structure. The classes were specifically added for my structure. In your scenario, access input and label directly with the error class as shown below.

/*========================================
Errors
========================================*/
input.error  {
  border: 2px solid red;
}
label.error  {
  color: red;
}

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

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Remain concealed once the lights dim

Looking for a way to fade out a logo in a preloader div after a call, but having issues with it becoming visible again once fully faded out. Ideally, I would like to keep it faded out or set it to display none using only CSS, although I can use jQuery if n ...

Show a flash message and error notification following an AJAX call in Laravel

When making an ajax request successfully, I need to display a flash message in my view. For instance, after editing something, I want the user to be redirected to the homepage with a message like "$flash = Your changes have been saved". It's simple to ...

How to Apply "novalidate" in Bootstrap 4 for Custom Form Validation in Rails 5.1

I am testing out Bootstrap 4 forms and its native validation for the first time. After running this code, I noticed that default error messages show up because I did not set the novalidate value. <%= form_tag contact_path, class: "needs-validation", m ...

Determine the sum of all the values entered into the text fields

On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 w ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

"In the most recent version of THREE.js (r82), the shadow is not detectable

I am having trouble casting a shadow from a cube onto a plane using MeshLambertMaterial in my code. Despite setting up the scene correctly, the shadows are not appearing as expected. Most solutions I have come across suggest that objects should be within ...

Changing Json Data into SQL Database Table

I'm looking for a way to dynamically generate SQL queries. I came across this helpful tool: http://querybuilder.js.org/demo.html Here is the JSON object I have: { "condition": "AND", "rules": [ { "id": "name", "field": "name", ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Path of the HTML5 database in Blackberry WebWorks

When referencing the Blackberry WebWorks API guide for HTML5 Database, I came across a crucial note: Note: For 5.x devices, an SD card is a necessary storage method for databases. To initialize a database, you can use this code snippet: db = window.open ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

jQuery AJAX returning an unexpected null value instead of JSON data

I'm currently working on a contact form that uses AJAX to submit data to a PHP file for processing. However, I'm facing some issues with retrieving the JSON object back into the AJAX command as it keeps returning null. Below is the code snippet t ...

Tips for optimizing search functionality in Angular to prevent loading all data at once

An exploration for information within vast datasets is triggered by AngularJS when the input contains more than 3 characters. var app = angular.module('test_table', []); app.controller('main_control',function($scope, $http){ $scope ...

Tips for extracting a substring from a string in JavaScript or ReactJS

Is there a way to extract a specific string from a website URL in ReactJS? For example, if the URL is https://www.mrkashyap.com/users/manish, I only want to retrieve the word manish or anything after users/. I currently have the URL stored in a variable ...

The TypeScript compiler does not allow a 'number' type to be assigned to 0, 10, or 20, even when the number itself is 0

When testing out my code snippet on the playground for Typescript, an error appears on line 24. I discovered that the issue can be resolved by explicitly casting commands back to <IPlan[]>, but I wonder why this extra step is necessary. Property &a ...

The function window.dispatchEvent does not function properly in browsers such as Firefox, Safari, and IE

I am facing an issue where I need to resize my browser window in order to fix a problem with IScroll caused by a promise that alters the width of a very wide element. The trouble arises because the promise modifies the width after IScroll has already loade ...

Add a horizontal line between two div elements to create a visual division in the middle

Here is a snippet of my HTML/CSS/JS code: <div id="blockcart-wrapper"> <div class="blockcart cart-preview"> <div class="header"> <a rel="nofollow" href="#"> <img class="cart-icon" src="https://via.placehold ...

Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during ...

Learn the steps to effortlessly upload a file with the record insert wizard in Dreamweaver using php

Below you will find the PHP code for inserting data: <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_ ...

Managing clicks outside a specified Component using React Higher Order Components

I have a desire to create a Higher Order Component that can manage clicks outside a specified component. This component will trigger a specific function when a user clicks outside the defined boundaries. The HOC requires two parameters: BoundaryComponent ...