Do not trigger popup if mandatory field is left blank

I am currently working on a contact form where, upon clicking the send button, a popup appears to confirm that the privacy policy has been read. The form does not submit if there are any empty required fields, but the popup still appears. I need to modify the code to prevent the popup from appearing if there are unfilled required fields.

$('#myCheck').click(function() {
     $(this).toggleClass("checked");
});


(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

$('.checkz').click(function () {
    $('#invias').toggleDisabled();
    $('#invias').toggleClass("activ3");
    });


$(".pex").click(function (e) {
e.stopPropagation();
});

function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}

//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})

checkInputs()
.checkz {width:20px; height:20px; background: transparent; background-size: contain; border:1px solid #CCC; border-radius:5px; display:inline-block; margin-bottom: 5px; margin-right: 10px;} 

#invias {opacity:0.5}

.activ3 {opacity:1 !important}

#popup {
background-color: rgba( 231, 135, 74, 0.85 );
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1999999999;
overflow: initial;
transition: all .15s ease-in-out;
}

.pex {width:500px;padding:30px;background:#FFF;z-index:1999999999;margin: 10% auto 0;text-align: center;}

.cst {display: inline-block; text-align: left;}

.checked {background-image: url(https://image.flaticon.com/icons/png/512/3/3596.png)}

button:disabled {opacity:0.5 !important}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

function popupshow() {
document.getElementById("popup").style = "";
}

function popupban() {
document.getElementById("popup").style.display = "none";
}
</script>

<form method="post" name="contactform" class="peThemeContactForm">
<div class="col-md-5 col-sm-5 col-xs-12 animated hiding" data-animation="slideInLeft">
<div class="form-group">
<input type="text" name="author" class="form-control input-lg" placeholder="Name*" required />
</div>
<div class="form-group">
<input type="email" name="email" class="form-control input-lg" placeholder="Email*" required />
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control input-lg" placeholder="Phone">
</div>
</div>
<div class="col-md-7 col-sm-7 col-xs-12 animated hiding" data-animation="slideInRight">
<div class="form-group">
<textarea name="message" class="form-control input-lg" placeholder="Message*" required ></textarea>
</div>
</div>
<a onclick="popupshow()" class="btn btn-custom up animated hiding" data-animation="fadeInUpBig" id="confirm">Send message</a>

<div id="popup" style="display:none;">
<div class="pex">
<div class="checkz" id="myCheck"></div> <div class="cst">Dichiaro di aver letto, compreso ed accettato <br>l'<a href="http://www.iwiz.it/privacy-policy" target="_blank" style="text-decoration:underline">informativa sul trattamento dei miei dati personali</a></div>
<br><br><a class="btn btn-custom" onclick="popupban()" >Close</a> <button type="submit" class="btn btn-custom" id="invias" onclick="popupban()" disabled>Accept</button>
</div>
</div>

You can access the test fiddle here: http://jsfiddle.net/2BgdD/12/
Thank you!

Answer №1

By declaring isValid as a global variable, you can implement a pre-check before triggering the popupshow method:

function popupshow() {
  if (!isValid) return;
  document.getElementById("popup").style = "";
}

However, it is important to make modifications to your checkInputs method as well:

function checkInputs() {
  $('input').filter('[required]').each(function() {
    if ($(this).val() === '') {
      $('#confirm').prop('disabled', true)
      isValid = false;
    } else {
      isValid = true;
    }
  });
  if(isValid) {$('#confirm').prop('disabled', false)}
  return isValid;
}

See the Updated Demo Here

Answer №2

const displayPopup = () => {
    if(validateInputs()) document.querySelector("#popup").style.display = "block";
}

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

Implementing dynamic content updating in WordPress by passing variables and utilizing AJAX

Currently, I am working on a shopping page that displays a list of all the stores. To streamline the user experience, I have created a sidebar containing various categories and implemented pagination within the store listings. These lists are generated thr ...

JSON data returned from an AJAX request could be utilized to populate a

Need help with displaying data in two dependent select boxes based on the selection of the first box. <?php $con=mysql_connect("localhost","root","root"); mysql_select_db("register",$con); ?> <!DOCTYPE html> <html&g ...

Confirmation from SimpleModal and redirecting to the original destination url

I've been searching for a solution without any luck. It seems like I might be missing something simple. What I need is a standard jQuery confirmation, like this: $('.confirm').click(function(){ var answer = confirm('Delete '+ ...

Creating a hierarchical structure for the Category Model in Sequelize using self-referencing

My database has a Category Table that uses a "parent" column: +----+--------------+--------+ | id | name | parent | +----+--------------+--------+ | 1 | Service | null | | 2 | Lifestyle | null | | 3 | Food & Drink | 2 | | ...

IE8 encounters a failure with window.execScript

I specialize in working with Ruby on Rails version 3.2.11 and jQuery version 1.9.1. One of the features I developed for my app is a chat system using JavaScript. Everything works smoothly on IE9, but I encountered an issue on IE8 when executing the follow ...

Having trouble retrieving the value from the $scope variable

Includes application module app.js var appProfileDetails = angular.module('profileDetailsApp', [ 'ngMaterial','ngAria','ngAnimate','ngRoute']); This module conta ...

When a user hovers over one div, a different div smoothly appears and stays visible as long as the user continues hovering over

Within my container div, alongside the article's title, there exists a hidden div (positioned absolutely next to the title and outside the container) that holds the article's image and truncated text. Here's what I aim for: When a user hove ...

Rails 6 does not have support for matching multiple route parameters

routes.rb: get '/get_text_by_tablenum/:filename_id/:tablenum_id', to: 'dashboard#get_text_by_tablenum' ajax: $.ajax({ dataType: "json", cache: false, url: '/get_text_by_tablenum/' + filename + &apo ...

Using AJAX to update the content within a div element

This div contains important information that I need to display. <div class="right-content"> </div> Within this div, data is loaded via AJAX. A specific piece of HTML has a link as shown below: <%= link_to job_applicants_path(j.id), :class ...

`How can I use jQuery to send a message to a p:messages component?`

Could I display a message using jQuery in the p:messages component below? <p:messages id="messageId" autoUpdate="true" closable="true" redisplay="false" /> I want to showcase an error message like this: jQuery(#messageId).val("Error message"); Wo ...

Utilizing ngRepeat to build intricate rows within a table

I have a unique collection that appears as follows: { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, } }, "14": { "10 ...

Navigate to a specific assignment labelled as "foo"

My approach to this problem involves using divs with specific titles. <div id="foo"></div> <div id="foo2"></div> <div id="foo3"></div> <div id="foo4"></div> <a class ...

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...

What is the best way to submit a form using PHP to send an email, implement Ajax for seamless transitions, and display a message next to the form without any screen refresh?

Upon clicking the submit button, I am looking to achieve two things: (1) Sending the form data via email using PHP without refreshing the page. (2) Displaying a thank you message next to the form utilizing Ajax. Most of the functionality is in pl ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Is it possible to search LinkedIn using just one keyword?

Is it possible to search for a LinkedIn profile using a single string instead of separate first and last names? The issue is that I only have a single name field in my database... Typically, one would construct a dynamic URL like this: http://www.linkedin ...

Enhancing the appearance of text in an article by using hover effects, while ensuring the link is attached to the

As I work on the design of my website, I am faced with a challenge involving elements that have links attached to them. I want visitors to be able to click anywhere on the article and be directed to a specific page. The code snippet I currently have is as ...

methods for transforming a string into an object

let styleValues = "{ "background-color": "#4a90e2", "padding": 10px }"; JSON.parse(styleValues); The code snippet above triggers the error below: Uncaught SyntaxError: Unexpected token p in JSON at position 46 ...

Adding PHP array to a JavaScript array

I am working with an array that contains the following data: Array ( [0] => Array ( [id] => 9826 [tag] => "php" ) [1] => Array ( [id] => 9680 [tag] => "perl" ) ) My goal is t ...