How can I use jQuery to prevent a click function from running when input fields are left empty

I have step cards with input fields on each card. A "Next" button is provided for each card to change the view.

However, I need to prevent the "Next" button from functioning if any input fields on the form are left empty.

Below is the code snippet:

var $currentCard, $nextCard, $prevCard;

var animationEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
var operationName = ["Order number", "Operation barcode", "Nest number", "Layers number", "Cycles number"];

$('.next').on('click', function (e) {
        e.preventDefault();
        $currentCard = $(this).parent().parent();
        $nextCard = $currentCard.next();


        $('#bar li').eq($('.card').index($nextCard)).addClass('active');
        var inAnimation = 'animated slideInLeft';

        $currentCard.hide();

        $nextCard
            .show()
            .addClass(inAnimation)
            .one(animationEvents, function () {
                $(this).removeClass(inAnimation);
            });
});

$('.prev').on('click', function (e) {
    e.preventDefault();
    $currentCard = $(this).parent().parent();
    $prevCard = $currentCard.prev();

    $('#bar li').eq($('.card').index($currentCard)).removeClass('active');

    var inAnimation = 'animated slideInRight';
    $currentCard.hide();

    $prevCard
        .show()
        .addClass(inAnimation)
        .one(animationEvents, function () {
            $(this).removeClass(inAnimation);
        });
});
.title {
    margin-bottom: 30px;
    color: #020304;
}

.card {
    max-width: 500px;
    width: 90%;
    background: white;
    margin: 50px ;
    padding: 20px 30px;
    border-radius: 2px;
    -webkit-animation-duration: 0.2s;
    animation-duration: 0.2s;
}

.cardTitle {
    text-align: center;
    text-transform: uppercase;
    margin: 0;
}

.cardText {
    margin: 25px 0 40px 0;
    color: grey;
    text-align:center;
}

.card:not(:first-of-type) {
    display: none;
}

.actions {
    text-align: center;
}

.btn {
    width: 200px;
    background: #ffd42a;
    font-weight: bold;
    font-size: 14px;
    color: #000;
    display: inline-block;
    text-decoration: none;
    text-align: center;
    border-radius: 2px;
    padding: 10px 5px;
    margin: 10px 5px;
}

    .btn:hover {
        box-shadow: 0 0 0 2px white, 0 0 0 3px #27AE60;
    }

.barContainer {
    width: 100%;
    text-align: center;
}

.bar {
    counter-reset: step;
    margin: 0;
}

    .bar li {
        list-style-type: none;
        float: left;
        width: 20%;
        position: relative;
        text-align: center;
        font-size: 9px;
        color: white;
    }

@media all and (min-width: 500px) {
    .bar li {
        text-transform: uppercase;
        font-size: 10px;
    }
}

.bar li:before {
    content: counter(step);
    counter-increment: step;
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    border: 1px solid #ddd;
    display: block;
    text-align: center;
    margin: 0 auto 10px auto;
    border-radius: 50%;
    background-color: white;
    color: #333;
}

.bar li:after {
    content: '';
    position: absolute;
    width: 100%;
    height: 2px;
    background: #ffed2b;
    top: 15px;
    left: -50%;
    z-index: -1;
}

.bar li:first-child:after {
    content: none;
}

.bar li.active:before {
    background: #ffd42a;
    border: 1px solid #ffd42a;
    color: #000;
}

.bar li.active + li.active:after {
    background: #27AE60;
}

.bar li.active:first-child + li:after:not(.active) {
    background: white;
}

.input-style {
    margin: 20px auto;
    width: 86%;
    height: 40px;
    position: relative;
    border-bottom: 1px solid #ccc;
    text-align: center;
}

    .input-style input {
        width: 86%;
        height: 100%;
        padding: 0px 10px;
        border: none;
        font-size: 22px;
        text-align:center;
        outline: 0;
    }
  

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<ul class="bar" id="bar">
                <li class="active">Register new PO</li>
                <li>Scan PO barcode</li>
                <li>Scan Operation barcode</li>
            </ul>
        </div>
        <section id="cards">
            <div class="card">
                <h3 class="cardTitle">Register new PO</h3>
                <p class="cardText">Some description</p>
                <div class="actions">
                    <a href="#" class="btn next startCO">Register new PO</a>
                </div>
            </div>
            <div class="card" id="CoStep1">
                <h3 class="cardTitle">Scan PO barcode</h3>
                <p class="cardText">Some description</p>
                <div class="input-style">
                    <input type="text" placeholder="PO barcode">
                    <div class="style"></div>
                </div>
                <div class="actions">
                    <a href="#" class="btn prev">Prev</a>
                    <a href="#" class="btn next coButton">Next</a>
                </div>
            </div>
            <div class="card" id="CoStep2">
                <h3 class="cardTitle">Scan Operation barcode</h3>
                <p class="cardText">Some description</p>
                <div class="input-style">
                    <input type="text" placeholder="Operation barcode"> <button class="plusButton">+</button>
                    <div class="style"></div>
                </div>
                <div class="actions">
                    <a href="#" class="btn prev">Prev</a>
                    <a href="#" class="btn next coButton startCO">Start CO</a>
                </div>
            </div>
        </section>

While I already have a function in place to check for empty input fields, the "Next" button proceeds to the next page without validation.

My requirement is to add validation to the "Next" button, ensuring the input fields are filled before advancing.

Answer №1

I have implemented the following jQuery code:

if($('.POBarcode').is(":visible")){
  if($('.POBarcode').val().length == 0) return false;
}
if($('.Operation_barcode').is(":visible")){
  if($('.Operation_barcode').val().length == 0) return false;
}

I have also assigned a class to the below elements

<input type="text" class="POBarcode" placeholder="PO barcode">
<input type="text" placeholder="Operation barcode" class="Operation_barcode">

Now, the next button cannot be pressed until the visible input has a value.

Here is a working demo:

var $currentCard, $nextCard, $prevCard;

var animationEvents = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
var operationName = ["Order number", "Operation barcode", "Nest number", "Layers number", "Cycles number"];

$('.next').on('click', function(e) {
  e.preventDefault();
  
  if($('.POBarcode').is(":visible")){
    if($('.POBarcode').val().length == 0) return false;
  }
  if($('.Operation_barcode').is(":visible")){
    if($('.Operation_barcode').val().length == 0) return false;
  }
  
  $currentCard = $(this).parent().parent();
  $nextCard = $currentCard.next();
  
  $('#bar li').eq($('.card').index($nextCard)).addClass('active');
  var inAnimation = 'animated slideInLeft';

  $currentCard.hide();

  $nextCard
    .show()
    .addClass(inAnimation)
    .one(animationEvents, function() {
      $(this).removeClass(inAnimation);
    });
});

$('.prev').on('click', function(e) {
  e.preventDefault();
  $currentCard = $(this).parent().parent();
  $prevCard = $currentCard.prev();

  $('#bar li').eq($('.card').index($currentCard)).removeClass('active');

  var inAnimation = 'animated slideInRight';
  $currentCard.hide();

  $prevCard
    .show()
    .addClass(inAnimation)
    .one(animationEvents, function() {
      $(this).removeClass(inAnimation);
    });
});
.title {
  margin-bottom: 30px;
  color: #020304;
}

.card {
  max-width: 500px;
  width: 90%;
  background: white;
  margin: 50px;
  padding: 20px 30px;
  border-radius: 2px;
  -webkit-animation-duration: 0.2s;
  animation-duration: 0.2s;
}

.cardTitle {
  text-align: center;
  text-transform: uppercase;
  margin: 0;
}

.cardText {
  margin: 25px 0 40px 0;
  color: grey;
  text-align: center;
}

.card:not(:first-of-type) {
  display: none;
}

.actions {
  text-align: center;
}

.btn {
  width: 200px;
  background: #ffd42a;
  font-weight: bold;
  font-size: 14px;
  color: #000;
  display: inline-block;
  text-decoration: none;
  text-align: center;
  border-radius: 2px;
  padding: 10px 5px;
  margin: 10px 5px;
}

.btn:hover {
  box-shadow: 0 0 0 2px white, 0 0 0 3px #27AE60;
}

.barContainer {
  width: 100%;
  text-align: center;
}

.bar {
  counter-reset: step;
  margin: 0;
}

.bar li {
  list-style-type: none;
  float: left;
  width: 20%;
  position: relative;
  text-align: center;
  font-size: 9px;
  color: white;
}

@media all and (min-width: 500px) {
  .bar li {
    text-transform: uppercase;
    font-size: 10px;
  }
}

.bar li:before {
  content: counter(step);
  counter-increment: step;
  width: 30px;
  height: 30px;
  line-height: 30px;
  font-size: 14px;
  border: 1px solid #ddd;
  display: block;
  text-align: center;
  margin: 0 auto 10px auto;
  border-radius: 50%;
  background-color: white;
  color: #333;
}

.bar li:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background: #ffed2b;
  top: 15px;
  left: -50%;
  z-index: -1;
}

.bar li:first-child:after {
  content: none;
}

.bar li.active:before {
  background: #ffd42a;
  border: 1px solid #ffd42a;
  color: #000;
}

.bar li.active+li.active:after {
  background: #27AE60;
}

.bar li.active:first-child+li:after:not(.active) {
  background: white;
}

.input-style {
  margin: 20px auto;
  width: 86%;
  height: 40px;
  position: relative;
  border-bottom: 1px solid #ccc;
  text-align: center;
}

.input-style input {
  width: 86%;
  height: 100%;
  padding: 0px 10px;
  border: none;
  font-size: 22px;
  text-align: center;
  outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<ul class="bar" id="bar">
  <li class="active">Register new PO</li>
  <li>Scan PO barcode</li>
  <li>Scan Operation barcode</li>
</ul>
</div>
<section id="cards">
  <div class="card">
    <h3 class="cardTitle">Register new PO</h3>
    <p class="cardText">Some description</p>
    <div class="actions">
      <a href="#" class="btn next startCO">Register new PO</a>
    </div>
  </div>
  <div class="card" id="CoStep1">
    <h3 class="cardTitle">Scan PO barcode</h3>
    <p class="cardText">Some description</p>
    <div class="input-style">
      <input type="text" class="POBarcode" placeholder="PO barcode">
      <div class="style"></div>
    </div>
    <div class="actions">
      <a href="#" class="btn prev">Prev</a>
      <a href="#" class="btn next coButton">Next</a>
    </div>
  </div>
  <div class="card" id="CoStep2">
    <h3 class="cardTitle">Scan Operation barcode</h3>
    <p class="cardText">Some description</p>
    <div class="input-style">
      <input type="text" placeholder="Operation barcode" class="Operation_barcode"> <button class="plusButton">+</button>
      <div class="style"></div>
    </div>
    <div class="actions">
      <a href="#" class="btn prev">Prev</a>
      <a href="#" class="btn next coButton startCO">Start CO</a>
    </div>
  </div>
</section>

Answer №2

Here is an example of what you can do in your upcoming click:

if ($('input', $currentCard).val() === '' && $(this).text() !== 'Register new PO') {
   return;
}

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

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

Bootstrap 5's h-100 feature functions flawlessly in Chrome, however, it encounters issues when used with a group

Can you please refer to this question: Issue with Aspect Ratio of Images in Bootstrap 5 due to Padding After applying the h-100 solution, everything looks great on Chrome. Unfortunately, when I check it in Safari, the aspect ratio of the image gets distor ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Is there a way to access the value of a variable within a loop inside a function and store it in a global variable?

I am struggling to retrieve the value of a variable after it has passed through a loop. I attempted to make it a global variable, but its value remains unchanged. Is there any way to achieve this? Below is my code snippet where I am attempting to access t ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

Is there a way to export the HTML table content to an Excel sheet that is compatible with browsers such as Internet Explorer, Mozilla Firefox, and others?

Welcome to my HTML Page! <html> <head> <title>Table </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> </script> </head> <body> <table ...

Switching up the default font style within TinyMCE

After successfully changing the default font within the editor using the guidelines provided here, I have encountered a new issue. The original default font no longer appears in the font drop-down list. The previous default font was Verdana, and the new d ...

Having trouble retrieving data from the MongoDB database using Node.js

Having trouble with data retrieval from MongoDb Successfully connected to MongoDb, but when using the find command, it should return an empty collection, yet nothing is being returned. What could be causing this issue and how can it be monitored through ...

Using JQUERY to toggle classes conditionally

$('.showall').css("cursor","pointer").click(function() { $('.value-container').toggle(); $('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : & ...

Sending HTML form information to PHP isDomainAvailable function

I am in the process of creating a website monitoring system. I have constructed an HTML form to collect data and send it to a PHP script, but I am encountering some difficulties. The HTML form is a standard one that uses the GET method. Here is my PHP cod ...

Unable to send form data to PHP script

Looking for assistance with passing a variable from a number input to a PHP page. HTML CODE <input type="number" class="count count-disco" name="quantity_disks" autocomplete="off" placeholder="0"> https://i.sstatic.net/BK3X9.png PHP and JQUERY CO ...

Efficiently Updating Multiple Highcharts Charts Using a Single Function

I have 4 different charts displayed on this page. <div id="section"> <div id="all" style="min-width: 400px; height: 400px; margin: 0 auto"></div> <div id="top10" style="min-width: 400px; height: 400px; margin: 0 auto">< ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Automatically updating the scope of the .filter() function

Is there a way to update the filter in the code below? .controller('MainCtrl', ["$rootScope", "$scope", function($rootScope, $scope) { $rootScope.number = 1; $scope.text = "foo|baz|bar" }]).filter("MyFormat", ["$rootScope", function($rootS ...

Using Angular to populate textboxes with SQL data

I am encountering an issue with a mat-table that retrieves its data from a database. One of the columns needs to be editable by the user so that they can update the content and reflect changes in the database. The problem lies in loading the data into the ...

Tips for designing a three-line label: positioning text in the middle, above, and below

I have a label that looks like this: https://i.sstatic.net/q0DaR.png Is there a way to position 'Lorem ipsum' perfectly in the center between 'dolor' and 'amet'? https://i.sstatic.net/aJapG.png - reference image T ...

How do I retrieve two input values using script code in Ajax?

Currently, I am facing a challenge with implementing two input values in my database search using AJAX. While the script code works well for one input value, it performs poorly with two input values. Below, you will find the codes that I have used. Firstly ...

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...

Encountered an error while attempting to insert a new user into a MySQL database using the Node, Express, and MySQL package

Currently in the process of creating a CRUD API using NodeJS. My main goal at the moment is to execute a POST request to add a new user to the database. The issue I am facing is that although I can successfully add a new user to the database, my server cra ...

AngularJS: Users must click submit button twice for it to function properly

It's puzzling that I have to click the submit button on my form twice before it triggers the save function below. My HTML is written in Pug format. Below is a snippet of my HTML template: <form ng-submit="save()"> <div class="form-group" ...