Activate the Submission Button Once Validation is Complete

My form consists of multiple input fields with validations. Initially, the submit button is disabled. Each time I enter a field, the validation function should run immediately. After all fields are filled with valid input, the submit button should be enabled. However, the code I tried below does not seem to work.

if($('input').val() == true) {
           $('.myButton').prop("disabled", false);
        }

I need assistance resolving this issue.

View jsfiddle here

JavaScript (JS)

function validateForm() {
    val = true;
    var firstName = $('#firstname').val();
    if (!firstName) {
        $('#firstname').siblings(".error").addClass('alert-on');
        val = false;
    }
    var lastName = $('#lastname').val();
    if (!lastName) {
        $('#lastname').siblings(".error").addClass('alert-on');
        val = false;
    }

    var input = $('#email');
    var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
    var is_email = re.test(input.val());
    if (!is_email) {
        $('#email').siblings(".error").addClass('alert-on');
        val = false;
    }

    return val;
}
$(function () {
        $('.myButton').prop("disabled", true);
    $("input").on("change keyup paste", function () {
        if (!$(this).val()) { $(this).siblings('.error').addClass('alert-on'); }
        else { $(this).siblings('.error').removeClass('alert-on'); }
    });
        if($('input').val() == true) {
        $('.myButton').prop("disabled", false);
    }
    $("#form").submit(function (event) {
        if (validateForm()) {
            return;
        };
        event.preventDefault();
    });

})

HTML Markup

<form id="form">
        <div class="">
            <input type="text" placeholder="First name*" id="firstname">
            <div class="error">Required</div>
        </div>
        <div class="">
            <input type="text" placeholder="Last name*" id="lastname">
            <div class="error">Required</div>
        </div>
        <div class="">
            <input type="email" id="email" name="email" placeholder="Email">
                <div class="error">A valid email address is required</div>  
        </div>
        <div class="">
            <input type="text" placeholder="Phone*" maxlength="12" id="phone">
            <div class="error">Required</div>
        </div>

        <div id="form_submit">
            <button class="myButton" type="submit">
                Submit
            </button>
        </div>
</form>

Cascading Style Sheets (CSS)

input {
  display: list-item;
  margin-bottom: 10px;
}
.error {
  display: none;
  color: red;
}
.alert-on {
  display: block;
}

.myButton{
  height: 40px;
  width: 90px;

}

Answer №1

To ensure the validity of each input, it is important to validate them individually. Here's an example code snippet to achieve this:

http://example.com/validation-code

var counter = 0; // Initialize count
$("input").on("change keyup paste", function () {
    if (!$(this).val()) { $(this).siblings('.error').addClass('alert-on'); }
    else { $(this).siblings('.error').removeClass('alert-on'); }        

    // Check validation for each input
    $('input').each(function(index, item){
      var inputValue = $(this).val();
      var validationErrors = $(this).closest('div').find('.alert-on').length;
      if(inputValue == "" || validationErrors > 0){
        counter++;
      }          
    })
    // Enable button if all inputs pass validation
    (counter == 0) ? $('.myButton').prop("disabled", false) : $('.myButton').prop("disabled", true);

    // Reset count after validation
    counter = 0;
});

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

Utilizing exceptions for specific objects in CSS

My table CSS includes the following code: .table-hover>tbody>tr:hover { background-color: #f36f25; color:#FFFFFF; } I am looking for a way to exclude specific rows from this hover effect. Is there a method to customize which rows trigger t ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

Ways to retrieve a single variable periodically and refresh it at intervals

One common issue faced by maintenance employees at my company is losing their log entry if they receive a call or text while filling out the daily form on their phones. To solve this problem, I came up with a solution to store the form values in PHP SESSIO ...

"Comparing the integration of Javascript and CSS within an HTML file versus linking them from an

When it comes to including external javascript and CSS files, is there a noticeable difference compared to including all javascript and CSS files (including jQuery core) directly within the HTML file using <style>...</style> and <script> ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...

Does SCSS have a specific 'self' identifier?

I am looking to incorporate SCSS styles on the body by default, and then reapply them specifically to the P and LI tags (since I do not have complete control over the site and want to prevent plugins from interfering with my p's and li's). To ac ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

Show me how to customize the default confirmation box using just CSS!

Is it possible to style the standard window.confirm using only CSS without any additional JavaScript code? If so, how can this be achieved? ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

How can I ensure that the Bootstrap datePicker is validated as a required field

I am using the it-date-datepicker as a calendar picker, which is a bootstrap-datepicker version based on ab-datepicker. The issue I am facing is that I need to make this field mandatory. I downloaded jquery.validate.js for this purpose but I can't see ...

Whenever I try to install the PostCSS plugin in Tailwind CSS and run "npm run build," an error always pops up. I've attempted to troubleshoot multiple times without success. Any suggestions on what I should try next?

When using Windows PowerShell, the following commands are executed: cd D:\TailwindCSS cd gs3 npm run build Output [email protected] build D:\TailwindCSS\gs3 postcss ./src/tailwind.css -o ./public/tailwind.css internal/modules/run_m ...

I'm wondering why my .focus() function is causing the cursor to move to the start of my contenteditable div?

I am currently developing a website for writing books, primarily using php. I have implemented a jQuery function that, upon clicking the "New Chapter" button, triggers an AJAX function along with various other JS/jQuery events. One of these events is inten ...

The constant frustration of trying to extract a predefined AJAX return value, only to

My Ajax call and PHP function are causing an issue in Firefox. Despite receiving an HTTP 200 status, the response shows the value "false," but it is not being passed to the success part of the Ajax handler - instead, I always get undefined. I have plenty ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Ways to avoid grid overflow

As a newcomer to CSS grid, I am struggling to understand how to prevent components from overflowing a grid. The section in question, with the class name of profile-widget-wrapper, is defined with grid-row:2/4 but is overflowing the grid. Can anyone provide ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

Understanding the concept of nested menus in ASP.NET

A table displaying a list of items with their corresponding details is shown below: ItemID MENU ParentID ImgUrl ----------- -------------------- ----------- ----------- 1 Home 0 ...

Retrieve the ID from the database and showcase the content on a separate page

My database has a table named "apartments," and I am using the following code to display its contents on a single page: $connect = mysqli_connect("localhost","root","","db_dice"); $query = "SELECT * FROM apartment ORDER BY ID DESC"; $records = mysqli_quer ...

Anomaly in Form Validation with Semantic-UI

This time around, I am implementing Semantic-UI with React. In the past, I have successfully utilized Semantic-UI's form and form validation features in various projects without encountering any issues. However, a new problem has arisen, which I will ...

Using JavaScript and jQuery to create a delay when handling input events

I am working on a project where I have an HTML table that retrieves its values from a database using jQuery Ajax. Here is an example: <div id="tableId"></div> Below is the JavaScript code: function showUser(rowsToShow) { request = $.get("s ...