jQuery disable form submit in less than xx seconds - javascript

I have a user registration form.I need to check if user form filled in less than xx seconds(5 seconds). If less than 5 seconds disable the form submit. Some thing like that disable the submit button click or return false or like that.
I wrote some jquery scripts.But not correctly working.
Here is the sample form.
<form id="registerform" class="registerform" method="post"/>
<input type="text" name="username" id="username" />
<input type="text" name="email" id="email" />
<input type="submit" name="submit" id="submitBtn" value="Submit" />
</form>
Here is the jquery scripts.
<script type=javascript>
jQuery.noConflict();
jQuery(document).ready(function ($) {
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
var checktime = 0;
jQuery('form#registerform').find(':input').each(function(){
jQuery(this).keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
jQuery(this).keydown(function(){
clearTimeout(typingTimer);
});
});
function doneTyping () {
checktime = typingTimer;
return checktime;
}
jQuery('form#registerform').submit(function() {
checktime = doneTyping ();
var timerInsec = (doneTypingInterval/1000);
if(checktime < timerInsec) {
return false; // disable form submit
} else {
// if user take to fill the form more than 5 seconds, submit the form
return true;
}
});
});
</script>
I need to integrate to the wordpress registration form.That's why I tried.
If anyone have a solution/solutions to this please help me. Really appreciate that.
Thank you

This will disable your submit button for 5 seconds:
var submitButton = $('#submitBtn');
submitButton.prop("disabled", true);
setTimeout(function() {
submitButton.prop("disabled", false);
}, 5000);
Online example
You would also want to make sure, that the malicious user doesn't submit the form by other means! Make sure to run server-side validation:
if ( isset($_SESSION['last_submit_time']) ) {
$delay = intval($_SESSION['last_submit_time']) + 5;
if ( time() < $delay ) {
$_SESSION['last_submit_time'] = time();
echo "You must wait for 5 more seconds before submitting. Timer reset.";
exit;
}
}

typing timer does not contain the time , instead it contains an id for the timer thats currently ticking...and since key up will always set it to some value, it will never be false.
Also, you add add and reset timer for each input. If you want the user to spend at least 5 seconds to fill in your form, dont enable the submit button until 5 sec has passed.
function doneTyping () {
checktime = typingTimer;//will always have a value that evaluates to true
return checktime;
}

Try that... HTML:
<form id="registerform" class="registerform" method="post">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
jQuery:
jQuery(document).ready(function ($) {
var intervalTime = 5000,
inputID = "#submit";
function initialize(interval, input) {
intervalTime = interval;
inputID = input;
jQuery(inputID).prop("disabled", true);
startCouting();
}
function startCouting() {
setTimeout(function() {
enableInput();
}, intervalTime);
}
function enableInput() {
jQuery(inputID).prop("disabled", false);
};
initialize(5000, "#submit");
});

Related

how can i make my submit button clickable once and still execute my php?

I have tried solving this but no matter what i try the button doesn't stay disabled for more than a second and won't execute my PHP script.
I have a restart button on my web page that when clicked sends an email to the admin to let them know a restart has been requested. I want this to be able to be clicked once then become greyed out to prevent multiple clicks. I want it to become active again after a certain amount of time
How can I get the Restart button to become clickable once (to rule out the possibility for too many script executions) and still execute the PHP script?
This is my code:
<form action=index.php method= "post">
<input type="submit" value="Request Restart" id="alertTimerButton" name="clickMe" onclick="countClicks();"/>
<?php
if (isset($_POST['clickMe']))
{
exec("/anaconda3/bin/python /Users/shoot_station_5/Sites/simpleblogs/restartemail.py \"$input_val\"");
} else{
}
I have tried adding various javascript such as:
function disable()
$(document).ready(function(){
$('.once-only').submit(function(){
$(this).children('button').prop('disabled', true);
alert("Thankyou a restart has been requested.");
});
});
and
<script type="text/javascript">
var ClickCount = 0;
function countClicks() {
var clickLimit = 1; //Max number of clicks
if(ClickCount>=clickLimit) {
alert("a restart has already been requested");
return false;
}
else
{
ClickCount++;
alert("Thankyou a restart has been requested.");
return true;
}
}
You have to change
onclick="countClicks();"
to
onclick="return countClicks();"
then your 2. solution does work.
Your 1. solution has multiple bugs. Don't wrap the code in a disable() function. And there is a # missing before 'button'.
I would do it like this:
onclick="disabled=true;"
That's enough.
Because you commented that you don't get your second solution running, here is the code:
var ClickCount = 0;
function countClicks()
{
var clickLimit = 1; //Max number of clicks
if (ClickCount >= clickLimit)
{
alert("a restart has already been requested");
return false;
}
else
{
ClickCount++;
alert("Thank you a restart has been requested.");
return true;
}
}
<form action="#" method="post">
<input type="button" value="Request Restart" id="alertTimerButton" name="clickMe" onclick="return countClicks();"/>
</form>
Well the button is working as intended. Since you don't use ajax/xhr here you reload your page when the form is submitted. That's why the button is resetted. If you don't want to use ajax/xhr just save your "status" and maybe the time in a session variable and change the button property according to it. Your html/php would look like this
session_start();
if (isset($_POST['clickMe'])) {
$_SESSION['restarted'] = time();
}
session_write_close();
$timeout = 300; // 5 min
$timer = time();
$disabled = false;
if (isset($_SESSION['restarted']) && ($timer - $_SESSION['restarted']) < $timeout) {
$disabled = true;
}
.. (html stuff) ...
<form action=test.php method= "post">
<input type="hidden" name="timer" value="<?php echo (isset($_SESSION['restarted']) ? $_SESSION['restarted'] : null)?>" />
<input type="submit" <?php echo ($disabled ? 'disabled="true"' : null)?> value="Request Restart" id="alertTimerButton" name="clickMe"/>
</form>
And your js like this (if you use jquery)
$(document).ready(function(){
$('form').on('submit', function(e){
alert("Thankyou a restart has been requested.");
return true;
});
var restart_time = parseInt($('input[name="timer"]').val());
var cur_time;
setInterval(function(){
cur_time = Math.floor(Date.now() / 1000);
if (cur_time - restart_time > 300000) {
$('#alertTimerButton').prop('disabled', false);
}
}, 5000);
});
Edit: I fixed the code a bit and added a time check in javascript.

Redirecting after submit with counter

I am trying to redirect with counter to another page. I want the redirect to start when I have submit the form. I want to redirect to another page after submit form.
var count = 6;
var redirect = "https://www.google.com";
function countDown() {
var timer = document.getElementById("timer");
if (count > 0) {
count--;
timer.innerHTML = "This page will redirect in " + count + " seconds.";
setTimeout("countDown()", 1000);
} else {
window.location.href = redirect;
}
}
<form method="post">
<p>
<label>Name
<input type="text" name="textfield">
</label>
</p>
<p>
<input type="submit" name="Submit" value="Submit"><br>
</form>
<span id="timer">
<script type="text/javascript">countDown();</script>
</span>
</p>
A form submit is always a request to the server. You can either use ajax to perform the submission of the form or you can just count and submit the form afterwards.
To prevent your form from submitting when a user hits the button u can prevent the default behaviour like so:
$('input [type=submit]').on('click', function( event ) {
event.preventDefault();
// use your counter here
// when counter hits 0 just submit the form with
$('form').submit();
});
or use an ajax call:
$('form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: 'url/to/form/action',
data: $(this).serialize(),
method: "POST",
success: function() {
// start your counter
// REDIRECT
}
});
});
The Problem with the first method would be that you are just delaying the form submission.
In the second case u cant reliably tell when you will get an success (or error) response since the call is asynchrous. This will result in either a delay before your counter starts or a possible delay after your counter ends if the server didnt respond until then.
You can achieve a counter by using setInterval, and making a check until it hits 0 to redirect:
<form method="post">
<p>
<label>Name
<input type="text" name="textfield">
</label>
</p>
<p>
<input type="submit" name="Submit" value="Submit">
<br>
</form>
<span id="timer">This page will redirect in <span id="count"></span> second(s).</span>
<script type="text/javascript">
var count = 6;
var redirect = "https://www.google.com";
var elem = document.getElementById('count');
elem.innerText = count
setInterval(() => {
count--
elem.innerText = count
if (count == 0) {
window.location.href = redirect;
}
}, 1000)
</script>

Prevent multiple alert on "oninvalid" html

I was thinking, can i stop the alerts after the first?
I'll explain it better, every time I confirm the form, start an aler for every input that has oninvalid.
so if i have 10 inputs, i'll have 10 alarms. Is it possible to interrupt them after the first one?
<form>
<input type="text" oninvalid="alert('test1')" required />
<input type="text" oninvalid="alert('test2')" required />
<button>Send</button>
</form>
Fiddle: https://jsfiddle.net/9d1L5pxd/1/
You can consider doing something like I demonstrate below. Basically just add an event handler to the send button, which will call a validation function on your form each time it's clicked.
The validation function checks all the text type field values. If a text field with an invalid value is encountered, the function will return false (stop immediately).
If the function doesn't find any problems with the user input then it will return true. You can use the return value to determine if the form should be submitted or whatever if you need to.
var btnSend = document.getElementById('btnSend');
btnSend.addEventListener('click', function() {
var isValid = validateForm();
if (isValid)
console.log('Form is ready to submit.');
});
function validateForm() {
var formToValidate = document.getElementById('dataForm');
var elements = formToValidate.elements;
var i;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
//replace this with your actual validation
var invalid = elements[i].value.length == 0;
if (invalid) {
alert(elements[i].id + ' is invalid.');
return false;
}
}
}
return true;
}
<form id="dataForm">
<input id="field1" type="text" required />
<input id="field2" type="text" required />
<input id="btnSend" type="button" value="Send">
</form>

Javascript function gets called and then page resets back to initial state [duplicate]

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
The validation is setup working fine, all fields go red but then the page is immediately refreshed. My knowledge of JS is relatively basic.
In particular I think the processForm() function at the bottom is 'bad'.
HTML
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" />
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" />
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" />
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
<button id="form_send" tabindex="5" class="btn" type="submit" onclick="return processForm()">Send</button>
<div id="form_validation">
<span class="form_captcha_code"></span>
<input id="form_captcha" class="boxsize" type="text" name="form_captcha" placeholder="Enter code" tabindex="4" value="" />
</div>
<div class="clearfix"></div>
</form>
JS
$(document).ready(function() {
// Add active class to inputs
$("#prospects_form .boxsize").focus(function() { $(this).addClass("hasText"); });
$("#form_validation .boxsize").focus(function() { $(this).parent().addClass("hasText"); });
// Remove active class from inputs (if empty)
$("#prospects_form .boxsize").blur(function() { if ( this.value === "") { $(this).removeClass("hasText"); } });
$("#form_validation .boxsize").blur(function() { if ( this.value === "") { $(this).parent().removeClass("hasText"); } });
///////////////////
// START VALIDATION
$("#prospects_form").ready(function() {
// DEFINE GLOBAL VARIABLES
var valName = $('#form_name'),
valEmail = $("#form_email"),
valEmailFormat = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
valMsg = $('#form_message'),
valCaptcha = $('#form_captcha'),
valCaptchaCode = $('.form_captcha_code');
// Generate captcha
function randomgen() {
var rannumber = "";
// Iterate through 1 to 9, 4 times
for(ranNum=1; ranNum<=4; ranNum++){ rannumber+=Math.floor(Math.random()*10).toString(); }
// Apply captcha to element
valCaptchaCode.html(rannumber);
}
randomgen();
// CAPTCHA VALIDATION
valCaptcha.blur(function() {
function formCaptcha() {
if ( valCaptcha.val() == valCaptchaCode.html() ) {
// Incorrect
valCaptcha.parent().addClass("invalid");
return false;
} else {
// Correct
valCaptcha.parent().removeClass("invalid");
return true;
}
}
formCaptcha();
});
// Remove invalid class from captcha if typing
valCaptcha.keypress(function() {
valCaptcha.parent().removeClass("invalid");
});
// EMAIL VALIDATION (BLUR)
valEmail.blur(function() {
function formEmail() {
if (!valEmailFormat.test(valEmail.val()) && valEmail.val() !== "" ) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmail();
});
// Remove invalid class from email if typing
valEmail.keypress(function() {
valEmail.removeClass("invalid");
});
// VALIDATION ON SUBMIT
$('#prospects_form').submit(function() {
console.log('user hit send button');
// EMAIL VALIDATION (SUBMIT)
function formEmailSubmit() {
if (!valEmailFormat.test(valEmail.val())) {
// Incorrect
valEmail.addClass("invalid");
} else {
// Correct
valEmail.removeClass("invalid");
}
}
formEmailSubmit();
// Validate captcha
function formCaptchaSubmit() {
if( valCaptcha.val() === valCaptchaCode.html() ) {
// Captcha is correct
} else {
// Captcha is incorrect
valCaptcha.parent().addClass("invalid");
randomgen();
}
}
formCaptchaSubmit();
// If NAME field is empty
function formNameSubmit() {
if ( valName.val() === "" ) {
// Name is empty
valName.addClass("invalid");
} else {
valName.removeClass("invalid");
}
}
formNameSubmit();
// If MESSAGE field is empty
function formMessageSubmit() {
if ( valMsg.val() === "" ) {
// Name is empty
valMsg.addClass("invalid");
} else {
valMsg.removeClass("invalid");
}
}
formMessageSubmit();
// Submit form (if all good)
function processForm() {
if ( formEmailSubmit() && formCaptchaSubmit() && formNameSubmit() && formMessageSubmit() ) {
$("#prospects_form").attr("action", "/clients/oubc/row-for-oubc-send.php");
$("#form_send").attr("type", "submit");
return true;
} else if( !formEmailSubmit() ) {
valEmail.addClass("invalid");
return false;
} else if ( !formCaptchaSubmit() ) {
valCaptcha.parent().addClass("invalid");
return false;
} else if ( !formNameSubmit() ) {
valName.addClass("invalid");
return false;
} else if ( !formMessageSubmit() ) {
valMsg.addClass("invalid");
return false;
} else {
return false;
}
}
});
});
// END VALIDATION
/////////////////
});
You can prevent the form from submitting with
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
Of course, in the function, you can check for empty fields, and if anything doesn't look right, e.preventDefault() will stop the submit.
Without jQuery:
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', handleForm);
Add this onsubmit="return false" code:
<form onsubmit="return false">
That fixed it for me. It will still run the onClick function you specify.
Replace button type to button:
<button type="button">My Cool Button</button>
One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.
<form onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
You can use this code for form submission without a page refresh. I have done this in my project.
$(function () {
$('#myFormName').on('submit',function (e) {
$.ajax({
type: 'post',
url: 'myPageName.php',
data: $('#myFormName').serialize(),
success: function () {
alert("Email has been sent!");
}
});
e.preventDefault();
});
});
This problem becomes more complex when you give the user 2 possibilities to submit the form:
by clicking on an ad hoc button
by hitting Enter key
In such a case you will need a function which detects the pressed key in which you will submit the form if Enter key was hit.
And now comes the problem with IE (in any case version 11)
Remark:
This issue does not exist with Chrome nor with FireFox !
When you click the submit button the form is submitted once; fine.
When you hit Enter the form is submitted twice ... and your servlet will be executed twice. If you don't have PRG (post redirect get) architecture serverside the result might be unexpected.
Even though the solution looks trivial, it tooks me many hours to solve this problem, so I hope it might be usefull for other folks.
This solution has been successfully tested, among others, on IE (v 11.0.9600.18426), FF (v 40.03) & Chrome (v 53.02785.143 m 64 bit)
The source code HTML & js are in the snippet. The principle is described there.
Warning:
You can't test it in the snippet because the post action is not
defined and hitting Enter key might interfer with stackoverflow.
If you faced this issue, then just copy/paste js code to your environment and adapt it to your context.
/*
* inForm points to the form
*/
var inForm = document.getElementById('idGetUserFrm');
/*
* IE submits the form twice
* To avoid this the boolean isSumbitted is:
* 1) initialized to false when the form is displayed 4 the first time
* Remark: it is not the same event as "body load"
*/
var isSumbitted = false;
function checkEnter(e) {
if (e && e.keyCode == 13) {
inForm.submit();
/*
* 2) set to true after the form submission was invoked
*/
isSumbitted = true;
}
}
function onSubmit () {
if (isSumbitted) {
/*
* 3) reset to false after the form submission executed
*/
isSumbitted = false;
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form id="idGetUserFrm" method="post" action="servletOrSomePhp" onsubmit="return onSubmit()">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<input type="submit" value="Submit">
</form>
</body>
</html>
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
Most people would prevent the form from submitting by calling the event.preventDefault() function.
Another means is to remove the onclick attribute of the button, and get the code in processForm() out into .submit(function() { as return false; causes the form to not submit. Also, make the formBlaSubmit() functions return Boolean based on validity, for use in processForm();
katsh's answer is the same, just easier to digest.
(By the way, I'm new to stackoverflow, give me guidance please. )
In pure Javascript, use: e.preventDefault()
e.preventDefault() is used in jquery but works in javascript.
document.querySelector(".buttonclick").addEventListener("click",
function(e){
//some code
e.preventDefault();
})
The best way to do so with JS is using preventDefault() function.
Consider the code below for reference:
function loadForm(){
var loginForm = document.querySelector('form'); //Selecting the form
loginForm.addEventListener('submit', login); //looking for submit
}
function login(e){
e.preventDefault(); //to stop form action i.e. submit
}
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
http://jsfiddle.net/dfyXY/
$("#buttonID").click(function (e) {
e.preventDefault();
//some logic here
}
If you want to use Pure Javascript then the following snippet will be better than anything else.
Suppose:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Without Submiting With Pure JS</title>
<script type="text/javascript">
window.onload = function(){
/**
* Just Make sure to return false so that your request will not go the server script
*/
document.getElementById('simple_form').onsubmit = function(){
// After doing your logic that you want to do
return false
}
}
</script>
</head>
<body>
</body>
</html>
<form id="simple_form" method="post">
<!-- Your Inputs will go here -->
<input type="submit" value="Submit Me!!" />
</form>
Hope so it works for You!!
Just use "javascript:" in your action attribute of form if you are not using action.
In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.
How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?
A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.
<form id="prospects_form" method="post">
<input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
<input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
<input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
<textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>
Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.
<form onsubmit="myFunction(event)">
Name : <input type="text"/>
<input class="submit" type="submit">
</form>
<script>
function myFunction(event){
event.preventDefault();
//code here
}
</script>
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work?
This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
I hope this will be the last answer
$('#the_form').submit(function(e){
e.preventDefault()
alert($(this).serialize())
// var values = $(this).serialize()
// logic....
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="the_form">
Label-A <input type="text" name='a'required><br>
Label-B <input type="text" name="b" required><br>
Label-C <input type="password" name="c" required><br>
Label-D <input type="number" name="d" required><br>
<input type="submit" value="Save without refresh">
</form>
You can do this by clearing the state as below. add this to very beginning of the document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}

Javascript - Enable Submit button when all input is valid

So I have a form with some inputs (First and last name, user name, birthday, password and email) with some validation conditions which I made like this for example :
function checkfnlname(field) {
curr = document.getElementById(field).value;
if ( curr.length > 0) {
updateCSSClass(field, 1);
return true;
}
else {
updateCSSClass(field, 0);
return false;
}}
This changes it's color and return true . I call these function using onKeyUp="". Now what I want to do is make the Submit button disabled until all the fields have been completed and validated by the functions up there. I wrote this function :
function formvalid() {
if (checkfnlname('fname') && && (all other fields)) {
document.getElementByID("submitinput").disabled = false;
}
else {
document.getElementByID("submitinput").disabled = true;
}
return 1;}
But I have no idea how/where to call it. (I tried a lot of things I found but nothing worked)
Is this the right way to do it ? if so how can I call this function ?
Here's a pure ES6 and HTML5 way.
You can watch your form for changes and then check to see if the form is valid.
const form = document.getElementById('form');
form.addEventListener("change", () => {
document.getElementById('submitBtn').disabled = !form.checkValidity()
});
I have modified an example from MDN to show this in action -> https://jsfiddle.net/denov/hxf3knob/2/
My approach:
function updateCSSClass(a, b) {
}
function checkfnlname(field) {
curr = document.getElementById(field).value;
if (curr.length > 0) {
updateCSSClass(field, 1);
return true;
} else {
updateCSSClass(field, 0);
return false;
}
}
window.onload = function () {
var btnSubmit = document.getElementById('submit');
// disable submit
btnSubmit.setAttribute('disabled', 'disabled');
// attach the keyup event to each input
[].slice.call(document.querySelectorAll('form input:not([type="submit"])')).forEach(function (element, index) {
element.addEventListener('keyup', function (e) {
// compute the number of invalid fields
var invalidFields = [].slice.call(document.querySelectorAll('form input:not([type="submit"])')).filter(function (element, index) {
return !checkfnlname(element.id);
});
if (invalidFields.length == 0) {
// reenable the submit if n. of invalid inputs is 0
btnSubmit.removeAttribute('disabled');
} else {
// disable submit because there are invalid inputs
btnSubmit.setAttribute('disabled', 'disabled');
}
}, false);
});
}
<form action="http://www.google.com">
First name:<br>
<input type="text" name="firstname" id="firstname"><br>
Last name:<br>
<input type="text" name="lastname" id="lastname"><br>
User name:<br>
<input type="text" name="username" id="username"><br>
Birthday:<br>
<input type="date" name="birthday" id="birthday"><br>
Password:<br>
<input type="password" name="password" id="password"><br>
email:<br>
<input type="email" name="email" id="email"><br>
<input type="submit" value="submit" id="submit">
</form>
It's simple, invoke button enable/disable function on within your type/value check function, something like this-
function checkfnlname(field) {
//here you can perform input check
curr = document.getElementById(field).value;
if ( curr.length > 0) {
updateCSSClass(field, 1);
return true;
}
else {
updateCSSClass(field, 0);
return false;
}
// to check button validations
formvalid();
}
Going this way, every time you type in the form it'll check it whether the condition for button matches or not, and will function accordingly.!
You need to call the validation function in the events.
// For example
<input type="text" onkeyup="validateForm()">
<select onchange="validateForm()"></select>
Second way:
Instead of using a submit button, use a normal button and call a function which checks your form items.
// Into the form or anywhere you want
<button type="button" onclick="validateForm()">Submit</button>
function validateForm() {
// Code to validate the form items
// if validated, send the form
// For example submitting a form with javascript
document.getElementById("myForm").submit();
}
The easiest way would be to call formvalid() onkeyup for every field. That function validates every field and shows the button if they are valid.
This should do the job, although it is not very efficient. It is a job in vain to check every field every time you type anything on any field. Ex: when you start on the first input there's no point in checking the last.
Instead you could have a check function that updates a global boolean variable when the field has valid data, and then the validate function to check the booleans instead of calling the check function. Then onkeyup in everyfield you should call both separately (first the check, then the validate).
Something like:
validFields=[];
function checkField(field) {
if (conditionIsMet) validFields[validFields.length]=field;
}
function validateForm() {
if (validFields.length==numberOfFields) ...
}
and
<input type="text" name="field1" value="" onkeyup="checkfield(this.name);validateForm()" />

Categories

Resources