简体   繁体   中英

add event listener + do not allow form submit

I have got simple registration form with submit button:

<input type="submit" value="" class="loginInput" id="submitReg" />

and javascript function to meassure time in miliseconds between page load and form submit:

(function () {
  var element = document.getElementById('submitReg'),
      start, end;

  window.onload = function (event) {
    start = +event.timeStamp; 
  };

  element.onclick = function (event) {
    end = +event.timeStamp;

    var diff = end - start; // time difference in milliseconds
    //alert(diff);
  };
})();

How to do it, to allow form submitting only if diff>3000 ? I guess I should add something like return true / return false , but I do not know how. Thanks for answers!!!

In your case, to submit form on condition - adjust your element.onclick event as shown below:

...
element.onclick = function (event) {
    end = +event.timeStamp;
    var diff = end - start; // time difference in milliseconds
    return (diff > 3000)? true : false;
};
...

You can just return true if the form is allowed to submit. Here is your code modified with a test "onsubmit" function:

(function () {
  var element = document.getElementById('submitReg'),
      the_form = document.getElementById('the_form'),
      current_time = document.getElementById('current_time'),
      start, end;

  window.onload = function (event) {
    start = +event.timeStamp; 
  };

  element.onclick = function (event) {
    end = +event.timeStamp;

    var diff = end - start; // time difference in milliseconds

    console.log(diff);

    //Allow the form to submit only after 3000 miliseconds
    if(diff > 3000){
      return true; 
    }
    return false;
  };

  //To test if this works...
  the_form.onsubmit = function(event){
    alert('Form submitted!');
  };
})();

Working example: https://codepen.io/sixfoot3/pen/qPzgQY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM