How to delay form submit? - javascript

I have a form that once the user clicks the Submit button - it runs 2 functions - (1) it pops up with a div that says 'Item added successfully to basket' then (2) a prefill function that sends the selected options to a Mals-E cart.
It works, but what i need to do is not let the form submit until the popup has shown for around 5 seconds - currently it flashes for a split second as the form is submitted immediately with the prefill function.
Can anyone help with this please?
Script Below:
function showDiv(f) {
document.getElementById('basket-center').style.display='block';
}
function prefill(f) {
var val = document.forms["basket"].elements["product[2]"].value;
val = val + gettext(document.forms["form"].elements['users']);
document.forms["basket"].elements["product[2]"].value = val;
document.forms["basket"].elements["price"].value = document.forms["form"].elements['sum'].value;
return false;
}
Form Script Here:
<form id="basket" name="basket" action="http://ww8.aitsafe.com/cf/add.cfm" method="post" onsubmit="showDiv(); prefill();">
<input name="userid" type="hidden" value="A1251773"/>
<input type="hidden" name="nocart"/>
<input name="product[]" type="hidden" value="{b}Sage 50 Accounts (The VAT Edition) 2014{/b}"/>
<input name="product[2]" type="hidden" value="{br}"/>
<input name="product[3]" type="hidden" value="{br}FREE Installation onto 1 Server/PC & Same Day Download when ordered before 3pm"/>
<input name="price" type="hidden" value=""/>
<input name="noqty" type="hidden" value="1"/>
<input name="thumb" type="hidden" value="sage50-thumb.png"/>
<input name="return" type="hidden" value="http://10.10.0.195/reality-solutions-development/sage-50-accounts.php"/>
<input type="image" src="img/buynow-button-green.jpg" border="0" alt="Buy Now" style="float:right; margin-top:-24px"/>
</form>

Try this:
//html
<form id="my_form">
<button id="my_button">submit</button>
</form>
//javascript
var my_form = document.getElementById("my_form"), button = document.getElementById("my_button");
my_form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
my_form.submit();
}, 5000);
return false;
}
Working jsfiddle: http://jsfiddle.net/njoqnwwf/

You could use Jquery for that
$(function() {
$('#form').delay(milliseconds).submit();
});

Related

Choosing among radio buttons and Text Field

I have 2 radio buttons. All of them have different values. I also have one text field, in case I need a different value, I can enter that value on that text field.
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="https://example.com/fee/25"> $25
<input type="radio" name="url" value="https://example.com/fee/50"> $50
<input type="submit" value="Submit">
</form>
and here is the Javascript I've found to make radio buttons working
<script type="text/javascript">
function doSubmit(form) {
var urls = form['url'];
var i = urls && urls.length;
while (i--) {
if (urls[i].checked) {
window.location = urls[i].value;
}
}
document.getElementById("amount").value;
return false;
}
</script>
I have one text field:
<input type="text" name="amount" size="10" id="amount" value="">
Ok. If the amount is entered, then I need to use this code:
document.getElementById("amount").value
But how to make it working with radio buttons? I have created this JS code:
<script type="text/javascript">
var link = "https://example.com/fee/";
var input= document.getElementById('amount');
input.onchange=input.onkeyup= function() {
link.search= encodeURIComponent(input.value);
};
</script>
What I'm doing wrong? Thanks in advance for your time. I love and enjoy learning from experts.
I would create a separate radio button for the text input:
var options = Array.from(document.querySelectorAll("[name=url]"));
amount.addEventListener('focus', function() {
options[0].checked = true; // If textbox gets focus, check that radio button
});
options[0].addEventListener('change', function() {
amount.focus(); // if first radio button gets checked, focus on textbox.
});
function doSubmit(form) {
// get checked value, replace empty value with input text
var value = options.find( option => option.checked ).value || amount.value;
window.location = "https://example.com/fee/" + value;
return false;
};
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="url" value="" checked>
$<input type="text" name="amount" size="5" id="amount" value="" >
<input type="radio" name="url" value="25"> $25
<input type="radio" name="url" value="50"> $50
<input type="submit" value="Submit">
</form>
Instead of using the url as the value for the radio buttons, consider using the value you wish to pass to the url:
function doSubmit(form) {
var endpoint = "https://example.com/fee/";
// gets the values of input elements that were selected
var checkedValues = Array.from(form.amounts)
.filter(radio => radio.checked)
.map(radio => radio.value);
// if a radio button was checked, use its value
// otherwise, use the value in the text field
var amount = checkedValues.length ?
checkedValues[0] : form.amount.value;
console.log('redirecting to: ', endpoint + amount);
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>
Edit: Wow I completely forgot you could use the :checked attribute as a css selector. In this case, the code becomes quite simple:
function doSubmit(form) {
// select checked inputs with the specified name attribute
var checkedRadio = document.querySelector('input[name="amounts"]:checked')
// if we have a radio button that is checked, use its value
// otherwise, use the text input's value
var amount = checkedRadio ? checkedRadio.value : form.amount.value;
window.location = 'https://example.com/fee/' + amount;
return false;
}
// uncheck radio buttons when text is entered
function uncheck() {
Array.from(document.querySelectorAll('input[name="amounts"]'))
.forEach(radio => radio.checked = false);
}
<form action="" onsubmit="return doSubmit(this)">
<input type="radio" name="amounts" value="25"> $25
<input type="radio" name="amounts" value="50"> $50
<input type="text" name="amount" onkeyup="uncheck()">
<input type="submit" value="Submit">
</form>

Delaying Form Submit

I want to delay the post of the below form by 3 seconds and have an image pop up.
<form id="test" name="test" method="post" action="">
<input type="hidden" name="inp1" method="post" value="<?php echo $var1 - $var2; ?>">
<input type="hidden" name="inp2" method="post" value="<?php echo $var3 - $var4; ?>">
<input type="hidden" name="inp3" method="post" value="">
<input type="submit" name="inp4" value="Test" />
</form>
I am trying to get the delay part working first and have tried using Javascript in the HTML head part of my php file:
$('test').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
form.submit();
}, 30000); // in milliseconds
});
This currently isn't giving any delay. Any ideas?
you forgot to add # with $("#test")
$('#test').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
form.submit();
}, 3000); // in milliseconds
});
Demo
I would switch things up a bit, rather than using a submit button I would change it to a regular button and pass the form in the button. You don't need the submit button at all.
<input type="button" name="inp4" value="Test" onclick="myfunction(form)" />
Then the function
function myfunction(form) {
setTimeout(function() {
form.submit();
},30000);
}
that should do the trick. No jQuery needed

why form is submitted while new window is open?

Hi I have the javascript function to open a new window and based on the value selected its populated the parent window field .But the problem is while open the new window the form is submitted .I just didn't attach the validation part. Can any body tell what might be the problem.
$(function() {
//Popup window for Nationlity
function nationalityPopUp() {
var nationalUrl="%bind(:9)";
new_Window = window.open(nationalUrl,"","width=220, height=500, left=250, top=50, scrollbars, resizable");
}
//Disable Parent Window
function parent_disable() {
if(new_Window && !new_Window.closed){
new_Window.focus();
}
}
<body onclick="parent_disable();">
<form name="Basicinfo" id="Basicinfo" method="post" action="%bind(:8)" onsubmit="return validateForm();">
<input type="text" name="Nationality" id="Nationality" value ="" />
<input type="image" src="%bind(:14)" name="Ntlylkp" onclick="nationalityPopUp();" />
</br></br>*Country Of Residency:
<input type="text" name="Residency_country" id="Residency_country" value ="" onblur="validateResCountry(value)"/>
<input type="image" src="%bind(:14)" name="Cntrylkp" onclick="countryPopUp();"/>
</br></br>*National Id:
<input id="Emirates_Id" name="Emirates_Id" type="text" value="" style="margin-left:10px;">
</br></br>*Marital Status:
<select name="marital_status" id="marital_status">
:%bind(:3);
</select>
</br> </br> *Regional Preference:
<select name="religious" id="religious">
:%bind(:4);
</select>
<input type="Submit" value="Submit And Next" style="float:right" >
</form>
</body>
return false while the for is submitted with jquery -
$('#Basicinfo').on('submit', function() {
if (some check needed) { // if want to add any check to submit the form or not
return false;
}
})

Revealing & Switching Between Hidden HTML Forms

I've read through a lot of tickets like this question but can't seem to get what I want to work. So I've had to ask this one.
I have 2 forms on a HTML page and 2 buttons.
Both forms are hidden using inline styling: style="display:none;"
What I want to do is reveal form 1 with button 1 and hide form 2, and button 2 to hide form 1 and show form 2.
Here is button 1:
<button type="button" id="button7">Click Here If your Serial Number is 549999 or Below</button>
Here is button 2:
<button type="button" id="button8">Click Here If your Serial Number is 550000 or Above</button>
This is form 1:
<form name="lowsearch" id="lowsearch" method="post" action="action.html" target="formresponse" style="display:none;">
<input TYPE="hidden" NAME="command" VALUE="search">
<input TYPE="hidden" NAME="file" VALUE="Repair_Project/R&S2Web.db">
<input TYPE="hidden" NAME="database" VALUE="Old_Serial">
<input TYPE="hidden" NAME="searchfields" VALUE="S_Serial_No;S_Description">
<p><b>Please enter your Serial Number</b></p>
<input TYPE="text" size="10" name="S_Serial_No" id="S_Serial_No" required>
<p><input TYPE="SUBMIT" NAME="b1" id="SUMBIT" VALUE="Find Device" class="buttonText"></p>
</form>
This is form 2:
<form name="highsearch" id="highsearch" method="post" action="action.html" target="formresponse" style="display:none;">
<input TYPE="hidden" NAME="command" VALUE="search">
<input TYPE="hidden" NAME="file" VALUE="Repair_Project/R&S2Web.db">
<input TYPE="hidden" NAME="database" VALUE="Serial">
<input TYPE="hidden" NAME="searchfields" VALUE="S_Serial_No;S_Description">
<p><b>Please enter your Serial Number</b></p>
<input TYPE="text" size="10" name="S_Serial_No" id="S_Serial_No" required>
<p><input TYPE="SUBMIT" NAME="b1" id="SUMBIT" VALUE="Find Device" class="buttonText"></p>
</form>
My issue is I don't know how to finish the Javascript to get the desired affect.
<script>
function func(a) {
var el;
if(a === 1) {
el = document.getElementById("lowsearch");
}
if(a === 2) {
el = document.getElementById("highsearch");
}
document.getElementById('button7').onclick = function () {
func(1);
};
document.getElementById('button8').onclick = function() {
func(2)
};
</script>
What you want to do is change the style property on the forms based on which one you want to show/hide. Inside the if blocks in your func function, you can set the property display values.
function func(a) {
if(a === 1) {
document.getElementById("lowsearch").style.display = "block";
document.getElementById("highsearch").style.display = "none";
}
if(a === 2) {
document.getElementById("lowsearch").style.display = "none";
document.getElementById("highsearch").style.display = "block";
}
}
You can view an example of it working at this fiddle: http://jsfiddle.net/thetimbanks/mzvkxr7d/

Simple Percentage Calculation of an Input Field with JQuery

I'm building a PayPal form that the user enters the amount and after that transfered to paypal,
everything is working fine but i need to add a calculation plugin to do the following,
If a user enters in the field 10$ (Calculate 10$-2%=8$) and return the result as text inside a span 8$
At the end of the form i have a "(p) paragraph" with a span id "site_commission_box" inside.
I need to show the calculated number inside this span.
Which JQuery plugin is good for use on this and how i can use it?
Any good example or tutorial to find out how i can do it?
Thanks a lot,
Philip
<form id="form_paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="business" value="mail#url.url"/>
<input type="hidden" name="cmd" value="_xclick"/>
<input type="hidden" name="return" value="http://returnpage.url"/>
<input type="hidden" name="cancel_return" value="http://cancelreturnpage.url"/>
<input type="hidden" name="rm" value="2"/>
<input type="hidden" name="currency_code" value="USD"/>
<input type="hidden" name="quantity" value="1"/>
<input type="hidden" name="item_name" value="Item Name"/>
<input type="hidden" name="item_number" value="Item ID"/>
<label>Amount (US$) : </label>
<input type="text" name="amount" id="input_amount" class="text" />
<input type="hidden" name="invoice" value="Post ID"/>
<input type="hidden" name="cbt" value="Make Payment →"/>
<input type="hidden" name="item_number" value="Item ID"/>
<input type="submit" name="submit" value="Confirm & Pay →" class="submit" />
<br/>
<span id="msg_moreamount" class="icon_warning red" style="display:none;">PayPal takes $0.35 commission for a $1 donation.</span>
<span id="msg_noamount" class="icon_warning red" style="display:none;">Please enter an amount and try again.</span>
<span id="msg_activity" style="display:none;"> <img src="loader.gif" align="middle" alt="load"/> Transferring to PayPal, please wait...</span>
<p>-2% of the price it will be <b>$<span class="text_decoration" id="site_commission_box"></span> USD</b>.</p>
</form>
Is there a reason you use jQuery() instead of $()?
Also, you should really cache your selected elements so you don't have to query the DOM multiple times for the same element.
Here's how I would do it:
$(function() {
// the minimum required value to be entered.
// in this case PayPal takes $0.35 from a $1
// donation, hence we ask for at least $1.35
var minimum_value = 1.35;
// cache elements that are used at least twice
var $amount = $("#input_amount"),
$msg = $("#msg"),
$commission = $("#site_commission_box");
// attach handler to input keydown event
$amount.keyup(function(e){
if (e.which == 13) {
return;
}
var amount = parseFloat($amount.val()),
commission = amount*0.02;
if (isNaN(commission) || isNaN(amount)) {
$msg.hide();
$commission.hide();
return;
}
if (amount <= minimum_value) {
$commission.hide();
$msg
.text("PayPal takes $0.35 commission for a $"+amount+" donation.")
.fadeIn();
} else {
$msg.hide();
$commission
.fadeIn()
.find("span")
.text((amount-commission).toFixed(2));
}
});
// attach handler to the form submit event
$('#form_paypal').submit(function() {
// check if there is an amount entered
if ($amount.val() > null) {
// is the amount equal to or higher than the minimum_value?
if ($amount.val() < minimum_value) {
// need more amount
// show more amount error
$msg
.addClass("icon_warning_red")
.text("Please enter an amount and try again.")
.fadeIn();
return false; // prevent the form from submitting
}
else {
// amount is more than minimum_value
// show activity
$msg
.removeClasss("icon_warning_red")
.html('<img src="loader.gif" align="middle" alt="load"/> Transferring to PayPal, please wait...')
.fadeIn();
return true; // submit the form
}
}
else {
// no amount entered at all
// show no amount error;
$msg.addClass("icon_warning_red").fadeIn();
return false; // prevent the form from submitting
}
});
});
You can see a working example here, there you can see the changes I did in the HTML as well.
You have to add a event-handler for a change event. Everytime if the input value is changed the discount is recalculated. See an example on http://jsfiddle.net/3sXZw/

Categories