HTML/Javascript Page is resetting after submitting form - javascript

I am working on learning to make forms using HTML and Javascript. When I go to submit my form, it processes it, and I can see the result, but the page quickly resets so that the form is back to its starting state. How can I make sure the page doesn't reset when the function is done?
Here is the HTML for the form and the function that processes it:
<form name="calculator" onsubmit="return calculate(this);">
Enter the value of the house: $
<input type="text" name="homeValue" id="homeValue" size="7" /><br>
<select name="selMortgage" id="selMortgage">
<option>Select a mortgage length</option>
<option>15-year mortgage</option>
<option>30-year mortgage</option>
</select></br>
<p class="form"><input type="checkbox" name="chkDiscount" value="discount"/>Good Credit Discount?</p>
<input type="submit" value="Calculate" />
<div id="result"></div>
</form>
function calculate(form) {
var amountEntered = form.homeValue.value;
var termLength;
var interestRate;
var calc;
document.getElementById("result").innerHTML = "hi";
if (!/^\d+(\.\d{1,2})?$/.test(amountEntered))
{
alert("You did not enter an amount of money");
//form.homeValue.focus();
return;
}
if (form.chkDiscount.checked == true)
{
interestRate = .05;
}
else
{
interestRate = .06;
}
if (form.selMortgage.selectedIndex == 0)
{
alert("Select a mortgage length");
}
else if (form.selMortgage.selectedIndex == 1)
{
termLength = 15;
}
else if (form.selMortgage.selectedIndex == 2)
{
termLength = 30;
}
calc = (Math.pow(1+interestRate,termLength) * amountEntered)/(termLength*12);
document.getElementById("result").innerHTML = calc.toFixed(2);
}

It looks like you are missing a return false.

Since you are submitting the form the values are lost due to page reload.
You may try to POST your values then assign the post values on your form elements so that even after refresh youre still able to see the POST data submitted..

Try this:
Just use return false; at the end of your javascript function.

When the form is submitted, the JS function calculate will be invoked. Since the function does not return any value, undefined will be assumed. And in JS the undefined will be assumed to nothing and the form will be submitted to server and reload again. This is why you lose your data. From your code, the page just execute some JS code. So we can prevent submitting the form to keep your data. You may need to return false in calculate function to prevent submitting. Example as below:
document.getElementById("result").innerHTML = calc.toFixed(2);
return false;

Related

How to save data from an input form after redirecting with javascript ONLY

I`m trying to keep the information from a form.
<form name="welcome_form">
<p>Prvi igrac: <input type="text" name="prvi"></p>
<p>Drugi igrac: <input type="text" name="drugi"></p>
</form>
<button onclick="submit_form();">Zapocni igru!</button>
Submit form validates data from input form, and redirects the user to another page.
How can i keep the data from the form on the redirected page
Without using jquery,php, just pure javascript.
I tried using cookies, but it didnt work for me.
var prvi_igrac,drugi_igrac;
function isValid(unos)
{
return /^\w{3,15}$/.test(unos);
}
function submit_form()
{
prvi_igrac = document.forms["welcome_form"]["prvi"].value;
drugi_igrac = document.forms["welcome_form"]["drugi"].value;
//alert(isValid(prvi_igrac));
if(isValid(prvi_igrac) == false || isValid(drugi_igrac) == false)
{
alert("Ime mora sadrzati 3-15 karaktera i samo slova,brojeve i donju crtu!");
return;
}
document.cookie = "prvi_igrac="+prvi_igrac;
var x = document.cookie;
alert(x);
}
Tnx in advance
You can use localstorage to store your form data on first page using following code.
localStorage.setItem('key', 'your data')
and then on redirected page yoou can get with below code
localStorage.getItem('key')

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

My javascript function in the code given below is getting called twice

The below code is a simple number guessing game.
The function guess() is getting called twice. I am at loss of logic why it's happening.
<!DOCTYPTE html>
<html>
<head><title>Number Guessing Game version 1.0</title></head>
<body>
<form onsubmit="guess();return false;">
<p><h2>I am your host, human. I am thinking of a number between 0 and 100, including both</h2></p>
<p><input type="text" id="inputId" autocomplete="off"></input><button id="submitButton" onclick="guess()">Guess!!</button></p>
<p><span id="msgId"></span></p>
<p>Guesses Remaining:<span id="guessId"></span></p>
</body>
</form>
<script language="javascript">
var doubleRandom = Math.random();
var guessesLeft = parseInt("10");
var intRandom = Math.round((doubleRandom*100));
var spanObj = document.getElementById("msgId");
var guessObj = document.getElementById("guessId");
guessObj.innerHTML=guessesLeft;
function guess()
{
var guessedNumber = document.getElementById("inputId").value;
alert(23);
if(guessedNumber==null || guessedNumber.trim()==''){
spanObj.innerHTML="Type something, human";
return;
}
if(isNaN(guessedNumber)){
spanObj.innerHTML="That better be a number, Human.";
return;
}else{
if(guessedNumber>100){
spanObj.innerHTML="That better be a number between 0 and 100, Human.";
return;
}else{
spanObj.innerHTML="";
}
}
var accurateAnswer = Math.round(guessedNumber);
var difference = guessedNumber-intRandom;
if(difference>45){
spanObj.innerHTML="That's way too high, Human";
return;
}else if(difference<-45){
spanObj.innerHTML="That's way too low, Human";
}else if(difference<=45 && difference>0){
spanObj.innerHTML="That's high, Human";
}else if(difference>=-45 && difference<0 ){
spanObj.innerHTML="That's low, Human";
}else{
spanObj.innerHTML="Bingo!! You got it!! Refresh to play agin.";
}
if(guessesLeft<=0){
spanObj.innerHTML="You have exhausted your number of guesses. Try again. Refreshing game....";
setTimeout("location.reload(true)", 3000);
}
guessesLeft=guessesLeft-1;
guessObj.innerHTML=guessesLeft;
}
</script>
</html>
That's because you are calling it twice: Once in the button's onclick event, and once in the form's onsubmit event. Delete one of them.
Change
<button id="submitButton" onclick="guess()">Guess!!</button>
to
<input type="submit" id="submitButton" value="Guess!!" />
This way, irrespective of if you click the button, hit enter, or use some other method to submit the form, your event will fire, once.
When you are hit the enter button the form is submitted. On form submit you have the function triggering.
What you could do is to make the button submit the form when clicked.
<button onclick="form[0].submit()">guess</button>
If the button is clicked the form is submitted, therefore the function in from submission is called on button click. This works on hitting enter as well. Both way the function is triggered only once.

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories