JavaScript form validation ensures that the data entered into a

My "this is required / missing fields" error message is triggering on focus out even though there is text entered into the field. I am confident it's a small issue that I am overlooking, but I can't seem to figure it out! I acknowledge that I am repeating a lot of code, but I couldn't find a way to avoid this repetition.

<h6 id="support_msg" class="lightblue">We support all</h6>
                 <h6 id="reg_error" class='light_red'></h6>
                      <form id="ajax_form" class="form-group col-sm-offset-2 col-sm-8" action="" method="post">


                        <label for="">First Name</label> <div id="err_fname" class="red">This is required</div>
                            <input type="text" id="reg_fname" class="form-control" placeholder="first name">
                        <label for="">Last Name</label> <div id="err_lname" class="red">This is required</div>
                            <input type="text" id="reg_lname" class="form-control" placeholder="last name">
                        <label for="">Username</label> <div id="err_uname" class="red">This is required</div>
                            <input type="text" id="reg_uname" class="form-control" placeholder="username">
                        <label for="">Email</label> <div id="err_email" class="red">This is required</div>
                            <input type="email" id="reg_email" class="form-control" placeholder="email">
                        <label for="">Password</label> <div id="err_pass1" class="red">This is required</div>
                            <input type="password" id="reg_pass1" class="form-control" placeholder="password">
                        <label for="">Verify Password</label> <div id="err_pass2" class="red">This is required</div>
                            <input type="password" id="reg_pass2" class="form-control" placeholder="verify password">
                        <label for="">State</label> <div id="err_state" class="red">This is required</div>
                                <input type="text" id="reg_state" class="form-control" placeholder="state">
                        <label for="">Age</label> <div id="err_age" class="red">This is required</div>
                                <input type="password" id="reg_age" class="form-control" placeholder="age">


                              <input id="reg_button" type="submit" value="REGISTER" class="form-submit form-control">

                    </form>
   var err_fname = false ;
   var err_lname = false ;
   var err_uname = false ;
   var err_email = false ;
   var err_pass1 = false ;
   var err_pass2 = false ;
   var err_state = false ;
   var err_age = false ;

   var fname = $('#reg_fname').val() ;
   var lname = $('#reg_lname').val() ;
   var uname = $('#reg_uname').val() ;
   var email = $('#reg_email').val() ;
   var pass1 = $('#reg_pass1').val() ;
   var pass2 = $('#reg_pass2').val() ;
   var state = $('#reg_state').val() ;
   var age = $('#reg_age').val() ;

$('#reg_fname').focusout(function(){

        check_fname() ;
}) ;

$('#reg_lname').focusout(function(){

        check_lname() ;
}) ;
$('#reg_uname').focusout(function(){

        check_uname() ;
}) ;

$('#reg_email').focusout(function(){

        check_email() ;
}) ;

$('#reg_pass1').focusout(function(){

        check_pass1() ;
}) ;

$('#reg_pass2').focusout(function(){

        check_pass2() ;
}) ;

$('#reg_state').focusout(function(){

        check_state() ;
}) ;
$('#reg_age').focusout(function(){

        check_age() ;
}) ;



        function check_fname () {
          //checking if blank fname and lastname
          if(fname == ''){
            $('#support_msg').hide() ;
            $('#reg_error').html('Missing Fields') ;
            $('#err_fname').show() ;
            err_fname = true ;
            return false ;
          }
          }

          function check_lname () {
            //checking if blank fname and lastname
            if(lname == ''){
              $('#support_msg').hide() ;
              $('#reg_error').html('Missing Fields') ;
              $('#err_lname').show() ;
              err_lname = true ;
              return false ;
            }
            }

            function check_uname () {
              //checking if blank fname and lastname
              if(uname == ''){
                $('#support_msg').hide() ;
                $('#reg_error').html('Missing Fields') ;
                $('#err_uname').show() ;
                err_uname = true ;
                return false ;
              }
              }

              function check_email () {
                //checking if blank fname and lastname
                if(email == ''){
                  $('#support_msg').hide() ;
                  $('#reg_error').html('Missing Fields') ;
                  $('#err_email').show() ;
                  err_email = true ;
                  return false ;
                }
                }


                function check_pass1 () {
                  //checking if blank fname and lastname
                  if(pass1 == ''){
                    $('#support_msg').hide() ;
                    $('#reg_error').html('Missing Fields') ;
                    $('#err_pass1').show() ;
                    err_pass1 = true ;
                    return false ;
                  }
                  }

                  function check_pass2 () {
                    //checking if blank fname and lastname
                    if(pass2 == ''){
                      $('#support_msg').hide() ;
                      $('#reg_error').html('Missing Fields') ;
                      $('#err_pass2').show() ;
                      err_pass2 = true ;
                      return false ;
                    }
                    }



                  function check_state () {
                    //checking if blank fname and lastname
                    if(state == ''){
                      $('#support_msg').hide() ;
                      $('#reg_error').html('Missing Fields') ;
                      $('#err_state').show() ;
                      err_state = true ;
                      return false ;
                    }
                    }


                    function check_age () {
                      //checking if blank fname and lastname
                      if(age == ''){
                        $('#support_msg').hide() ;
                        $('#reg_error').html('Missing Fields') ;
                        $('#err_age').show() ;
                        err_age = true ;
                        return false ;
                      }
                      }

Answer №1

This code snippet demonstrates the importance of applying the same class to all textboxes when implementing a function. By binding the focusout event to the class and accessing the current textbox value using $(this).val(), you can effectively handle logic for error checking. See the example below for a clearer understanding.

$(".test").bind("focusout", function(){    
 if($(this).val() == ''){
                $('#support_msg').hide() ;
                $('#reg_error').html('Missing Fields') ;
                $('#err_uname').show() ;              
                return false ;
              }

})

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

Create a package that is compatible with both node and browser environments

After successfully creating a node NPM package that acts as a wrapper for a specific JSON API using node's http, https, and querystring modules, I am now looking to expand its usability by making it compatible with browsers. This would involve replaci ...

What sets apart a string constant from a string enclosed in quotation marks? And what techniques exist to transform one into the other?

Calling an asynchronous function: const variable = 'something' await MyAsyncFunction.execute(variable) No output is displayed. But if I change it to: await MyAsyncFunction.execute('something') It works!! Can someone please explain h ...

What is the best way to use useCallback within loops?

I am currently exploring the concepts of memo and useCallback, and to better grasp them, I have created a simple example: import { memo, useCallback, useState } from "react"; import { Button, Text, TouchableOpacity, SafeAreaView } from "reac ...

What is the best method for storing and accessing audio files that users upload in my MERN application?

I am developing a MERN application and am looking to implement a feature that allows users to upload audio files. I have read that storing the files directly in the database or within a folder inside the app is not recommended. I need a solution that en ...

Retrieve data from jqgrid cell content

Within my jqgrid cells, I have incorporated both image and text using a formatter function as shown below: function myFormatter (cellvalue, options, rowObject) { switch(cellvalue){ case 'Unknown': newCell="<img src=&ap ...

Generate a variety of requests with Axios

I have a task where I need to send multiple Axios requests, but the number of requests can be completely random. It could range from 0 to even millions. Once all the requests are completed, I then need to perform an action, such as updating my state, which ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

Tips for integrating material UI sample snippets into a component

I have a specific goal in mind: to create a page with a header that says "Survey Start" followed by a user selection interface. My vision is to implement a simple component as follows: export class Survey extends Component { state = { } ren ...

Is there a way to achieve element scrolling similar to scrollLeft within a scrollable container without using JavaScript

Looking for a CSS Solution: Is there a way to achieve element.scrollLeft functionality in CSS without using javascript? I want to pre-scroll a scrollable container. Situation Overview: I have a scrollable container that houses various items. Some instanc ...

What is the process for submitting a form in Laravel 5 with ajax?

Struggling with understanding how to create an ajax post in Laravel. I would like to display errors using jQuery after validation, but I'm unsure about accessing the object sent to my controller and what needs to be 'returned' in the control ...

Mobile devices with a horizontal scroll

Having trouble with side scrolling on mobile devices. I've set two @media queries for tablet and mobile. Visit dev.bdbshop.com @media only screen and (max-width: 767px) { .wrap { max-width: 300px; } Could the issue be related to this? Any suggestio ...

"Enhance search functionality by integrating live search results with clickable hyperlinks

I am currently working on implementing a live search feature in Laravel 7. Everything is functioning correctly, however, I am facing an issue where I am unable to add a (href a tag) to the result list. The results are being displayed in a select option usi ...

Limit the number of API queries allowed in Node.js

In my quest to restrict queries made to the Battle.net API within their limits of 100 calls per second and 36,000 calls per hour, I am facing a challenge. The current implementation of my code is as follows: var async = require ('async'); var b ...

Tips for implementing two Secondary Actions in React Material UI, with one positioned on the left corner and the other on the right, while ensuring that the behavior of the

Is there a way to display two secondary actions on either end of a list item without triggering additional onclick events? The placement can be adjusted by overriding the CSS properties right and left. https://i.stack.imgur.com/rhr7N.gif The issue arises ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

Error: A colon was unexpectedly encountered while trying to access the JSON API on tickets.com

I've been attempting to retrieve data from the following URL: http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json To do this, I am ut ...

Displaying success and failure messages on a modal window using Ajax in PHP form

Unable to display error messages or success messages in the same modal window. I have set up Wordpress and using the following code: Form <form id="formcotizador" method="post" action="<?php echo get_template_directory_uri(); ?>/cotizador/procc ...

PHP code cannot be executed due to a problem with Angular routing

I stumbled upon this previous discussion during my search for assistance with a particular problem, but unfortunately there were no responses that could provide a solution. The issue I am facing involves submitting a form and expecting to receive a php va ...

Deselect radio option

I am attempting to create a Vue instance with a group of radio buttons. My aim is that when a user clicks on a checked radio button, it will become unchecked. However, I have not been successful in accomplishing this using Vue so far. Below is the code I h ...

What could be causing the issue with .html() not functioning properly on Internet Explorer 7?

My asp.net-mvc website is experiencing strange behavior in Internet Explorer 7 on a particular page. The HTML result of an AJAX call is not displaying on the screen, although it works perfectly fine in Firefox, Chrome, and IE8. Initially, I suspected that ...