Displaying a hidden div using the jQuery .each() method

Attempting to validate a form using jQuery, the goal is to target all form fields with class="required" and utilize the .each() function to verify if the field is empty. If it is empty, a hidden div positioned relative to the field should be displayed.

An issue arises as the provided code fails:

$('#application').submit(function(){
var requiredFields = $('.required').val();
requiredFields.each(function(){
    if (requiredFields == ''){
        position = requiredFields.position();
        width = requiredFields.outerWidth();
        $("#error-wrapper-mail").css({
            visibility: "visible",
            top: (pos.top - 8) + "px",
            left: (pos.left + width + 25) + "px"
        }).hide().fadeIn("slow").delay(2700).fadeOut("slow");
        requiredFields.addCLass("not-valid").focus().delay(3500).queue(function(){
            $(this).removeClass("not-valid");
        });
        return false;
    }
}); });

It works fine when selecting the input field by ID.

The HTML markup:

<form role="form" id="application" action="add-customer.php" method="post" enctype="multipart/form-data">
    <label for="Input-firstname">First name<span class="redstar"> * </span></label>
    <input type="text" class="form-control required" id="Input-firstname" name="firstname" placeholder="Your first name">
    <br />
    <label for="Input-lastname">Last name<span class="redstar"> * </span></label>
    <input type="text" class="form-control required" id="Input-lastname" name="lastname" placeholder="Your last name">
    <br />
    <label for="InputPass">Password<span class="redstar"> * </span></label>
    <input type="password" class="form-control  required" id="InputPass" name="pass" placeholder="Choose your password">
    <span class="help-block">Please create a password more than 6 symbols long, including uppercase letters, lowercase letters and digits.</span>
    ...
</form>

Seeking guidance from those experienced in jQuery as I navigate this new territory.

EDIT: Access the fiddle here - http://jsfiddle.net/7yLmq/

Answer №1

One possible strategy is to iterate through each element with the class $('.required'):

$('.required').each(function(){
   var requiredFields = $(this).val();
   // Insert your custom code here
});

Answer №2

To improve your code, consider utilizing other jQuery methods.

$('#application').submit(function(){
  $('.required').each(function(){
    if($(this).val() == ''){
      $(this).closest('.help-block').fadeIn();
      return false;
    }
  });
});

This code assumes there is one help-block for each required input field. You can modify it to show the help-block next to the current required field, but this may not be necessary unless you need dynamic loading of messages.

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 it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

Error loading console due to JSON data on website

After creating a Json data file named question.json with the following content: "Endocrinology":[ { "title":"Endocrinology", "id": "001", "date":"08J", "question":"In adult men, anterior pituitary insufficiency does not caus ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

Collaborative JavaScript repository within the Websphere Liberty platform

Is it possible to utilize a JavaScript library (such as Dojo, JQuery, or other custom developed libraries) as shared libraries within a Websphere Liberty server? For instance, I am interested in storing the .js files in either C:\wlp\usr\sh ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

The response from a jQuery ajax call to an MVC action method returned empty

I am working on an inventory application with the following layout: <body> <div class="container" style="width: 100%"> <div id="header"> blahblahblah </div> <div class="row"> <div id="rendermenu ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Disable Autocomplete Chip functionality when only one can be selected

When multiple is set to true, I prefer the Chip option. Is there a way to enable the Chip functionality even when multiple is set to false? <Autocomplete className={classes.search} options={top100Films} ge ...

Leveraging Variables within my .env Configuration

Does anyone have suggestions on how to set variables in my environment files? Website_Base_URL=https://${websiteId}.dev.net/api In the code, I have: websiteId = 55; and I would like to use config.get('Website_Base_URL'); to retrieve the compl ...

Developing a Chessboard Using JavaScript

Seeking help with a Javascript chessboard project. I have successfully created the board itself, but facing difficulty assigning appropriate classes (black or white) to each square. Managed to assign classes for the first row, struggling with the remainin ...

Whenever I use NextJS's <Link> component, I always end up getting redirected to a

After searching online, I came across this question and tried to implement the suggested solution, but it's still not working for me. Apologies for any duplication. I have a simple link tag that is resulting in a 404 error: <Link className={classe ...

What are the different ways you can utilize the `Buffer` feature within Electron?

When attempting to implement gray-matter in an electron application, I encountered the error message utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a method or workaround available to utilize Buffer within electron? ...

Having trouble with PHP form not functioning correctly?

Is there a way to display the var_dump with the 'selected country' information? I am having trouble due to an issue with the $res (array) $id. <?php if(isset ($_POST['submit'])) { $id = $_POST['cata']; $api = new ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

exploring the ins and outs of creating computed properties in TypeScript

How can I store an object with a dynamically assigned property name in an array, but unsure of how to define the array properly? class Driver { public id: string; public name: string; constructor(id , name) { this.id = id; th ...

How can I use VueJS and Vue Router to generate a details page for a list item?

I am currently working with a list of items sourced from a JSON file and looping through them. However, I want to create individual details pages for each item using VueRouter. Any advice on how I can accomplish this? I am facing difficulties in passing t ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...

Retrieve the value from an input tag that is only displayed based on a condition using *ngIf

In my HTML form, I have implemented conditional visibility of input fields based on the radio button selection using *ngIf. <table> <tr> <td><label>name</label></td> <td><input #name />&l ...