JavaScript function return not staying in browser - javascript

I am trying to create a very simple HTML site for my co-workers to use for calculating cellular phone pricing based on a formula. I have a form with user inputs to declare the full price of the phone, amount of down payment, etc. Basically everything seems to be working, however the returned answer from my formula in my JavaScript function only displays on the screen for a fraction of a second and the JavaScript seems to reload. Have I unintentionally caused a loop?
I am very new to JavaScript please let me know if I am leaving out any pertinent information to helping to solve this issue. I will include my code below.
<body>
<div id="container">
<form id ="formula">
<fieldset>
<legend> Finance Formula</legend>
<div id="label">
<label for="fullPrice">Full Price:</label>
<br />
<br />
<label for="downPay">Down Payment:</label>
<br />
<br />
<label for="discount">Discount:</label>
</div>
<div id="input">
<input type="text" id="fullPrice" name="fullPrice" />
<br />
<br />
<input type="text" id="downPay" name="downPay" />
<br />
<br />
<input type="text" id="discount" name="discount" />
</div>
</fieldset>
<input type="submit" id="submit" name="submit" onclick="financed();"/>
</form>
</div>
<div class="resultsBox">
<p id="result"></p>
</div>
<script type="text/javascript" language="javascript" charset="utf-8">
function financed(){
var fullPrice = document.getElementById('fullPrice').value;
var downPay = document.getElementById('downPay').value;
var discount = document.getElementById('discount').value;
console.log("The Total Amount Paid for Phone is:" +(((parseInt(fullPrice) - parseInt(downPay)) / 24) - parseInt(discount)) * 24);
};
</script>
</body>
</html>
I have also tried this script instead which is what I found when researching online.
<script type="text/javascript" language="javascript" charset="utf-8">
function financed(){
var fullPrice = document.getElementById('fullPrice').value;
var downPay = document.getElementById('downPay').value;
var discount = document.getElementById('discount').value;
document.getElementById('result').innerHTML = (((parseInt(fullPrice) - parseInt(downPay)) / 24) - parseInt(discount)) * 24;
};
</script>
Basically the end result I am looking for is the answer for the equation within the function to "print" onto the browser and stay there.

HTML elements have default behaviors when they're used-- forms, for instance, will refresh the page on submit. Fortunately, there is a preventDefault method that will stop this behavior. You can read more about it here and here.
You just need to add an event listener to your submit tag, like this:
document.getElementById("submit").addEventListener("submit", function(event){
event.preventDefault();
}

Normally form submit will navigate to the action attribute url, if there is no action attribute, navigate to same page. if you want to avoid this default behaviour you have to modify the tag or submit button like mentioned below.
<form id ="formula" action="javascript:void(0)">
or
<input type="button" id="submit" name="submit" value="clickme" onclick="financed();"/>

It is because your submit input reloads the page by default. Try removing the onClick from submit and calling this instead:
document.getElementById("submit").addEventListener("click", function(event){
event.preventDefault(); // preventing the default submit action
financed();
});

Related

Clear submitted form using JavaScript

I know this is continuously asked anew, and I've checked out different answers and tried different solutions but to no avail.
I just have to build a form that takes as input the cylinder ray and it height and then find the volume when we click a button.After finding it, shuold be cleared all fields with another button .The function to calculate volume it is working fine, but not the function that clear inputs.
Here is the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript">
function llogarit() {
var rreze = parseInt(document.getElementById("val1").value);
var lartesi = parseInt(document.getElementById("val2").value);
var rez = document.getElementById("llogarit");
rez.value = (Math.PI * Math.pow(rreze, 2) * lartesi);
}
function fshij() {
document.getElementById("val1").value.clear();
document.getElementById("val2").value.clear();
document.getElementById("llogarit").value.clear();
}
</script>
</head>
<body>
<form>
<p>Vendos 2 vlera</p>
<p>rreze
<input type="text" name="rreze" id="val1" value="2" /></p>
<p> lartesi
<input type="text" name="lartesi" id="val2" value="2" /></p>
<p> Vellimi
<input type="text" name="vellimi" id="llogarit" value="" /></p>
<input type="button" onclick="llogarit()" value="llogarit" />
<input type="reset" value="fshij" onclick="fshij()" />
</body>
</html>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
You can reset all form controls in one form with reset method.
// <form name="FORM_NAME">
document.forms["FORM_NAME"].reset();
Try the following:
document.getElementById('myInput').value = ''
Try the follow and add a div tag to the code
<div class="yourClass">
<button onclick="cdClear();" class="yourClass">Clear</button>
</div>
Note: In HTM, you can replace the class with id if you have already coded.
<script type="text/javascript">
function cdClear(){var a=document.getElementById("codes");a.value="",a.focus(),</script>

Form with two submit buttons doing two different things

I have a form that I have two buttons on. One button should take the user to one php script and the other button would take the user two a different php script. However for some reason the buttons aren't doing anything. Here is the code.
<script language="Javascript">
function OnButton1()
{
document.contactform.action = "../scripts/email-info.php"
// document.Form1.target = "_blank"; // Open in a new window
document.contactform.submit(); // Submit the page
return true;
}
function OnButton2()
{
document.contactform.action = "../scripts/email-info2.php"
//document.contactform.target = "_blank"; // Open in a new window
document.contactform.submit(); // Submit the page
return true;
}
</script
Then here is the actual form code:
<form id="contact-form" name="contactform" method="post">
<fieldset>
<div id="holder">
<div id="formLeft">
<div class="txtlabel">Name* </div><div class="input-bg"><input type="text"
name="name" id="name" required></div>
</div>
</div>
<div id="msgbox">
<div class="txtlabel">Tell Us About Your Business Needs</div>
<div class="message-bg">
<textarea name="message" id="message" rows="9" cols="56" required></textarea><input
name="formpage" type="hidden" value="<?=$pagename;?>" />
</div></div><div style="clear:both"></div><br /><br />
<input src="/submitbtn.jpg"
name="submit" value="View Now" class="submit-button" onclick="OnButton1();"/>
<input src="/submitbtn.jpg"
name="submit" value="Download Now" class="submit-button2" onclick="OnButton2();" />
</fieldset>
</form>
I've removed some of the submission fields to make it more easily viewable. But I get nothing when I click either button...Any thoughts??
problem is in input:
<input src="/submitbtn.jpg"
name="submit" value="View Now" class="submit-button" onclick="OnButton1();"/>
When you have a form:
document.contactform.submit
Javascript returns the input with name submit, not the submit function.
You could change the name of the input:
<input src="/submitbtn.jpg"
name="yourName" value="View Now" class="submit-button" onclick="OnButton1();"/>
Also, your inputs are not buttons, check this.
Update
This question mentions HTML5 formaction attribute:
<form action=#">
<buton formaction="script-1.php">submit one</button>
<buton formaction="script-2.php">submit two</button>
</form>
I'm surprised no one mentioned formaction. It is a legal attribute (in HTML5) for the input and button tag in submit/image state and can be used to send form data to a different action page. http://mdn.beonex.com/en/HTML/Element/input.html (it is also valid in button too).
<form action=#">
<buton formaction="script-1.php">submit one</button>
<buton formaction="script-2.php">submit two</button>
</form>
In case you need to support IE9-, you simply can polyfill this, using webshims.
<script src="webshims/polyfiller.js"></script>
<script>
webshims.polyfill('forms');
</script>
<!-- now it also works with IE8/9 and other legacy browsers -->
<form action=#">
<buton formaction="script-1.php">submit one</button>
<buton formaction="script-2.php">submit two</button>
</form>
The reference to your form is
document.forms.contactform
and not
document.contactform
So, for example, the submit button should be:
document.forms.contactform.submit();
// ^^^^^
The same correction should be applied to other references.

Javascript: unable to submit form

I'm trying to use javascript (used within another program) to automate the submission of a form with the appropriate textboxes filled in. Using the simple page below, I can successfully fill out the text box using:
javascript:document.getElementsByName('UserIDValue')[0].value = "12345";
but can't seem to get anything to work that will actually submit the form. None of these attempts at solving it work: (By 'work' I mean have the same effect as if I clicked the Log In button.)
document.forms["MFALogInForm"].submit();
document.getElementsByName("LoginButton")[0].submit();
document.getElementById("MFALogInForm").submit();
document.forms[0].submit();
the code for the page I'm working with is below: The link to it is here: https://ppcplus.121fcu.org/Mobile/Features/Auth/MFA/MFALogin.aspx
<html><body>
<form id="MFALogInForm" name="MFALogInForm" method="post" action="MFALogin.aspx?__ufps=981699">
<input type="hidden" name="__EVENTTARGET" value="">
<input type="hidden" name="__EVENTARGUMENT" value="">
<script language=javascript><!--
function __doPostBack(target, argument){
var theform = document.MFALogInForm
theform.__EVENTTARGET.value = target
theform.__EVENTARGUMENT.value = argument
theform.submit()
}
// -->
</script>
<img id="RoofImage" src="/Mobile/Images/Current_HandheldDevice/Universal/1Pixel.gif" alt="Private PC" /><br />
<img id="LogoHeader_LogoImage" src="/Mobile/Images/Current_HandheldDevice/Universal/Logo.gif" /><br />
<font size="+1" color="#006D9B"><b>LOGIN</b></font><br>
<font size="-1"><b>USER ID</b></font><br>
<input name="UserIDValue"/><br>
<input name="LoginButton" type="submit" value="Log In"/><input name="ResetButton" type="submit" value="Reset"/><br>
</form></body></html>
document.forms[0].elements["LoginButton"].click();
worked for me.

simple javascript error - Button click appends query string on form submit

I've got a simple form that when a button is clicked, it calculates a link via concatenation and outputs the link on the same page by overwriting an existing method. The page should not redirect anywhere, even to itself.
The problem is that it appends a query string to the URL (ie /linkgenerator.html becomes /linkgenerator.html?generatelink=Generate+Link#), which actually causes two things to happen :
1) The form submits the first time properly, and then immediately reloads the page again, losing your input. Once you submit it again on the reloaded page, you're okay.
2) The query string causes the script to not work -period- when running on the local file system in IE7
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SRP Link Generator</title>
<script language="javascript" type="text/javascript">
function dogeneratelink()
{
var code1= document.getElementById("code1").value;
var brand = document.getElementById("brand").value;
var code2= document.getElementById("code2").value;
var errors = checkerrors(prop, srp);
if (errors)
{
alert(errors);
return;
}
var link = "http://www." + brand + ".com/" + code1 + "/" + code2;
var a = document.getElementById("link");
a.href = link;
a.textContent = link;
}
function doclear()
{
var a = document.getElementById("link");
a.href = '';
a.textContent = '';
}
function checkerrors(code1, code2)
{
var errors;
var propset;
if (code1.length != 5)
{
errors = "You must enter a valid Code 1";
code1set = 1;
}
if ((code2.length < 4) || (code2.length > 5))
{
if (code1set == 1)
{
errors += " and Code 2";
}
else
{
errors = "You must enter a valid Code 2";
}
}
return errors;
}
</script>
</head>
<body>
<form action="#">
<h1>Link Generator</h1>
<div class="row">
<label>Code 1:</label>
<input type="text" id="code1" />
</div>
<div class="row">
<label>Brand:</label>
<select id="brand">
<option value="brand1">Brand 1</option>
<option value="brand2">Brand 2</option>
<option value="brand3">Brand 3</option>
</select>
</div>
<div class="row">
<label>Code 2:</label>
<input type="text" id="code2" />
</div>
<div class="row">
<div class="buttonrow">
<input type="submit" onclick="dogeneratelink()" id="generatelink" name="generatelink" value="Generate Link" class="button"/>
<input type="submit" onclick="doclear()" id="clear" value="Clear" class="button"/>
</div>
</div>
</form>
<div id="generatedlink"><a id="link"></a></div>
</body>
</html>
I've tried taking the action="#" out, but it doesn't seem to do anything.
All I want is the link to be calculated and immediately displayed on the screen.
Looking forward to your feedback! Thanks!
edit The form now behaves properly on submit, thanks to your advice of changing the submit type to a button.
The script works perfectly in Firefox. Unfortunately, I need it to work in IE7, and it doesn't. The validation alerts are being properly called, but the correct link is not being displayed on the page. Can anyone figure out what I did wrong?
I am not getting any Javascript errors or warnings.
edit again The last error was caused because I was using "textContent" and not "innerHTML"
Everything works now!
You don't need a form submission because you don't have to post anything to the server, all works are done by client side.
There are two ways to fix this:
add 'return false' to you onclick handler
<input type="submit" onclick="dogeneratelink(); return false" id="generatelink" name="generatelink" value="Generate Link" class="button"/>
<input type="submit" onclick="doclear(); return false" id="clear" value="Clear" class="button"/>
change the input type to button
<input type="button" onclick="dogeneratelink()" id="generatelink" name="generatelink" value="Generate Link" class="button"/>
<input type="button" onclick="doclear()" id="clear" value="Clear" class="button"/>
<form action="" onsubmit="return false;">
Replace <form action="#"> with <form> to post back to the current page, though this isn't a valid HTML technique, it works in all browsers.
Change the submit type in inputs. You don't need to send info somewhere else, then use a button
<button type="button" onclick="something();">Click Me!</button>
or styled a tag
Click Me!
Check out this working example, much simpler than what you're trying to do. Notice the link and where the link points to both change on clicking the button. You can add stuff to the textbox and it will change the link's href.
http://jsfiddle.net/BpEMA/1/
You've worked yourself into some very complicated code. Firstly, use jQuery (the learning curve is really small and the benefit is huge). Then, simplify what you're trying to do.

E-mail form interactivity

I'm a web development student and I need some help. I have the code below; How do I make it work only when the form is submitted and not the text field is clicked. I also would like it to get and insert the textField's value in the .thanks Div. Please help me learn.
<script type="text/javascript">
$(document).ready(function(){
$(".quote").click(function(){
$(this).fadeOut(5000);
$(".thanks").fadeIn(6000);
var name = $("#name").val();
$("input").val(text);
});
});
</script>
<style type="text/css">
<!--
.thanks {
display: none;
}
-->
</style>
</head>
<body>
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</p>
</form>
<div class="thanks"> $("#name").val(); Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
This is a bit rough and ready but should get you going
$(document).ready(function(){
$("#submitbutton").click(function(){
//fade out the form - provide callback function so fadein occurs once fadeout has finished
$("#theForm").fadeOut(500, function () {
//set the text of the thanks div
$("#thanks").text("Thanks for contacting us " + $("#name").val());
//fade in the new div
$("#thanks").fadeIn(600);
});
});
});
and I changed the html a bit:
<div id="theForm">
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="button" name="submitbutton" id="submitbutton" value="Submit" />
</label>
</p>
</form>
</div>
<div id="thanks">Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
There are several things at issue here:
By using $('.quote').click(), you're setting a handler on any click event on any element contained within the <form>. If you want to catch only submit events, you should either set a click handler on the submit button:
// BTW, don't use an id like "button" - it'll cause confusion sooner or later
$('#button').click(function() {
// do stuff
return false; // this will keep the form from actually submitting to the server,
// which would cause a page reload and kill the rest of your JS
});
or, preferably, a submit handler on the form:
// reference by id - it's faster and won't accidentally find multiple elements
$('#quote').submit(function() {
// do stuff
return false; // as above
});
Submit handlers are better because they catch other ways of submitting a form, e.g. hitting Enter in a text input.
Also, in your hidden <div>, you're putting in Javascript in plain text, not in a <script> tag, so that's just going to be visible on the screen. You probably want a placeholder element you can reference:
<div class="thanks">Thanks for contacting us <span id="nameholder"></span>, we'll get back to you as soon as possible</div>
Then you can stick the name into the placeholder:
var name = $("#name").val();
$('#nameholder').html(name);
I don't know what you're trying to do with the line $("input").val(text); - text isn't defined here, so this doesn't really make any sense.

Categories

Resources