How to delay on checkform using javascript? - javascript

I tried to delay for 10 sec before submit form like this but not work. It's will be still return true by not to delay.
<form class="form" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" >
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var test = "1";
setTimeout(function(){
if(test != '0'){
return false;
}
else
{
return true;
}
}, 10000);
}
</script>
I want to know, how to delay on checkform using javascript ?

You must return to the checkForm function. A return inside a callback does not return to the outer function. Even if it did it must be immediate, not 10 seconds later
You could use a flag so you can call the function again inside the delay by submitting the form again
var allowSubmit = false;
function checkform(form) {
if (allowSubmit) {
return true;
} else {
var test = "1";
setTimeout(function() {
if (test === '1') {
// when validation passes resubmit with updated flag
allowSubmit = true;
form.submit();
}
}, 10000);
return false;
}
}

Here is a better way to do it if you have jQuery library included. In your case, the page gets submitted to itself and gets refreshed, so your 10 seconds get reset.
<form class="form" method="post" action="" enctype = "multipart/form-data" >
<input type="submit" name="submit" value="OK">
</form>
$(function(){
$("form").bind("submit", function(e){
e.preventDefault();
e.stopPropagation();
var test = "1";
setTimeout(function(){
if(test != '0'){
//return false;
alert("false");
}else{
alert("true")
//return true;
}
}, 10000);
});
});

So the problem here is that a submit request is has the same outcome as if you were to return something in a function.
For example if you had something like this:
function returnExplanation(){
return 0;
console.log("You will never see me");
}
You will never see the text in the console after the return.
A submit functions the same. although there are a few other ways to make this happen, I made a few adjustments to your code to achieve what you were looking for.
<form class="form" id="submitForm" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="button" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#submitForm').on('click', function ()
{
var test = 1;
setTimeout(
function ()
{
if (test !== 0)
{
console.log("false");
return false;
} else
{
console.log("true");
return true;
}
}, 10000);
$('#submitForm').submit();
});
});
</script>
The first thing I did was give your form an "id". this allows jQuery (or javascript) to easily decipher exactly which element they should be communicating with.
Next, I removed your "onsubmit" attribute and added the appropriate jQuery to respond to the click event.
After that, I changed your button from a "submit" to a "button" type.
lastly, after the timeout, your form still submits with the line that reads:
$('#submitForm').submit();
I hope this helps you on your way to becoming a better HTML / jQuery programmer.

Related

Js script crashing entire element

I am making a site on google sites.
I have a button made by code that detects if you put a certain value into an input box, it should then load another site. But when I enter that correct value, the object crashes.
I've tried a lot of different things, but nothing works.
<form name="form1" method="GET">
<input name="codebox1" type="text" />
<input name="button1" type="submit" value="Check Code" onClick="return testResults(this.form)"/>
</form>
<script>
function testResults (form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.location = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
window.alert("Correct Code. Connecting...");
}
else {
window.alert("Wrong Code, try again!");
}
return false;
};
</script>
window.location = string; is wrong . You should use this to change the browser address. Also, alert must be executed before switching the page
change your function to this:
function testResults(form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.alert("Correct Code. Connecting...");
setTimeout(() => {
window.location.href = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
}, 0);
}
else { window.alert("Wrong Code, try again!"); }
return false;
}

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.

Problems with javascript / window.confirm function

I have an HTML button that calls the checkTax() function.
The function should either confirm and proceed with the form submit when OK is clicked, or cancel the submission and redirect the user to a different page.
This is the function:
function checkTax () {
if ( CUSTTAXRATE == 0 ) {
var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
if (r == true){
return true;
}
else {
<!--- return false; --->
window.location.replace("index.cfm?action=retailQuote.settings");
}
}
}
I have tried both just cancelling the submission or redirecting it, but I cant get either to work. Both ways still submit the form and proceed.
What am I doing wrong??
Make sure you use a return statement in the button's onclick attribute.
<button type="submit" onclick="return checkTax();">Submit</button>
Otherwise, the return value from the function will be ignored, and it won't prevent the form from submitting when it returns false.
I have tried completing the answers above for your simplification.
Please find the code below :
<body>
<form action="">
<input type=text id="t1">
<button type="submit" onclick="return checkTax();">Submit</button>
</form>
<script type="text/javascript">
function checkTax() {
var CUSTTAXRATE = document.getElementById("t1");
if (CUSTTAXRATE == 0) {
var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
if (r == true) {
return true;
} else {
window.location
.replace("index.cfm?action=retailQuote.settings");
return false;
}
}
}
</script>

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Two JavaScript functions onsubmit and onclick

I have two JavaScript functions to check two fields (input title and textarea)
form name="myform" onsubmit="return Checkthis()"
button type="submit" onclick="Checkthis();return false;"
Inside Checkthis() I call Check1() and Check2() and in onsumbit=/onclick=. I call only on Checkthis()
However, only the first function is checked onsubmit and onclick; I have tried to remove Checkthis() and call two functions like onClick="Check1();Check2();" but this doesn't work either.
function Check1() {
var msg_area = document.getElementById("mydiv1");
if () {
return false;
}
}
function Check2() {
var msg_areaa = document.getElementById("mydiv2");
if () {
return false;
}
}
function Checkthis() {
Check1();
Check2();
}
I have tried with: onsubmit ="Checkthis()" and onsubmit="return (Check1() && Check2());"
Any method I use only the first function is checked!
Okay this might not be a popular answer, so downvote away, but it will probably work.
Use jQuery:
$(document).ready(function(){
$("#wtvrDiv").click(function(){
Check1();
Check2();
});
});
To better explain my comments, give this a shot.
HTML:
<form name="myform">
<input type="text" id="titleID" />
<input type="text" id="textareaID" />
<button type="button" onclick="checkthis()">Submit</button>
</form>
Javascript:
var check1 = function () {...} // Don't submit, just see if it's valid
var check2 = function () {...} // Don't submit, just see if it's valid
var checkthis = function() {
if (check1 && check2) {
document.getElementById("myform").submit();
}
}
This page is also very helpful for getting started with form validation.

Categories

Resources