So I'm doing this for a summer class and I have to get this carpet calculator to display the result in a "Perform a document.write to display the results on a new html page." (quote taken straight from assignment). It says to use document.write and I grasp the concept of document.write after using some tutorials on w3 but when I try to apply it to my project, it has no effect on my web page.
Below is my code:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<link rel="stylesheet" href="http://www.w3.org/StyleSheets/Core/Oldstyle" type="text/css" />
<head>
<title>Tutorial Project 10</title>
</head>
<body>
<h1>Carpet Calculator</h1>
<form name = "carpet" action=" ">
</br>Enter the length of your room in feet</br><input name = "length" type = "text" />
</br>Enter the width of your room in feet</br><input name = "width" type = "text" />
</br>Typically an allowance is made for room irregularities and unavoidable waste.
</br>Enter the percent overage as an integer in the interval [0, 20]</br><input name = "overage" type = "text" />
</br></br><input name = "SqFt" type = "button" value = "Compute Square Feet " onclick = "ComputeSquareFeet()" />
</br></br><input name = "SqYd" type = "button" value = "Compute Square Yards" onclick = "ComputeSquareYards()" />
</br></br><input type = "reset" value = "Clear" />
</form>
<script type="text/javascript">
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
carpet.SqFtResult.value = SqFt+(SqFt*(carpet.overage.value / 100));
document.write(SqFtResult);
}
function ComputeSquareYards()
{
var SqYd = ((carpet.length.value/3)*(carpet.width.value/3));
carpet.SqYdResult.value = SqYd+(SqYd*(carpet.overage.value / 100));
document.write(SqYdResult);
}
</script>
</body>
</html>
The page works like this, the user enters data into 3 boxes, the button is pressed which calls the function and at the end of that function, it performs document.write. However, after doing a bunch of trial and error, I concluded that my formulas were working and the function was being called but the document.write wasn't for some reason.
Any ideas on what I'm doing wrong? Thank you!
Edit: I had a text box that displayed the result of the function just to make sure it was working but once I switched to document.write, nothing seemed to work
Seems like you need to write this to a new HTML page; for example try calling the below function with your text:
function writeToNewPage(text) {
var newPage = window.open("", "New Page","width=400, height=300, scrollbars=1, resizable=1");
newPage.document.open();
newPage.document.write(text);
newPage.document.close();
}
You can't use document.write on the current page without wiping the whole page, and it seems the assignment question does actually say a new page.
It seems to me that the problem there is not really the document.write, but probably the way you are getting the data from the form.
It should be something like:
document.forms["formname"][fieldname].value;
Also to create a variabe do it like:
var SqYdResult=somthing;
Hope it helps
Turns out I was getting ahead of myself
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
carpet.SqFtResult.value = SqFt+(SqFt*(carpet.overage.value / 100));
document.write(SqFtResult);
}
needs to be
function ComputeSquareFeet()
{
var SqFt = (carpet.length.value*carpet.width.value);
var SqFtResult = SqFt+(SqFt*(carpet.overage.value / 100));
document.write("Carpet needed in square feet: " + SqFtResult);
}
Because I wasn't declaring the variable it wasn't working. When I defined it I got the result I wanted.
Thank you all for your help!
Related
I am more the hardware guy and my programming skills really suck. I am trying to create things mostly by trial and error and the help of google. I am helping out some GFX-/Ad-Designers, who basically create stuff, place it on a website and have to run those websites thru severals browsers. I am trying to make this less manually handed.
This is run in a HTA. As I said, I am not a programming guy and this was something I could easly work with =/ probably some other language could do this by ease...but as said...
tl;dr
How do I get the value of id="text1" to be added at the end of the URL
shell.run("Firefox https://www.example.com=(text1.value)"); doesnt work.
I does work if I manually change the URL, but than I would not have a handy input-field and changing the URLs by hand...I guess the ad-creating ppl will mess up things.
So, thats what I have done so far...but I can't fix it.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Sub-Site Automation</title>
<hta:application applicationname="Run test on browsers" scroll="yes" singleinstance="yes">
<script type="text/javascript">
function openURL()
{
var input = document.getElementById("text1");
/* console.log(input); // Log
*/
var inputValue = input.value;
/* console.log(inputValue); // Log2
*/
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=(text1.value)");
shell.run("Chrome https://www.example.com=(text1.value)");
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=(text1.value)");
}
</script>
</head>
<body>
<input type="text" id="text1" Name="text1" value="Place ID of subwebsite here"><br>
<input type="submit" Value="Open in all Webbrowsers" onclick="openURL()">
</body>
</html>
Please help!
As I mentioned in the comments, the answer is in your code itself.
See the lines:
// This line gets the element you want
var input = document.getElementById("text1");
// This line gets it's value. You need this value
var inputValue = input.value;
The variable inputValue is what you need to replace there instead of using text1.value.
So your function would be as follows:
function openURL() {
var input = document.getElementById("text1");
var inputValue = input.value;
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=("+inputValue+")");
shell.run("Chrome https://www.example.com=("+inputValue+")");
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=("+inputValue+")");
}
the problem ist that you have no reference to the elements with id text1 so you can not access its value. A second problem is that you try to access a variable inside of a string literal which could be solved in es5 with string concatenation or in newer ecmascript versions with template literals.
Depending on the input value you should also use encodeURIComponent so that the resulting URL is valid.
One version that would work is the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Sub-Site Automation</title>
<hta:application applicationname="Run test on browsers" scroll="yes" singleinstance="yes">
</head>
<body>
<input type="text" id="text1" Name="text1" value="Place ID of subwebsite here"><br>
<input type="submit" Value="Open in all Webbrowsers" onclick="openURL()">
<script type="text/javascript">
function openURL()
{
var text1 = document.getElementById("text1");
var shell = new ActiveXObject("WScript.Shell");
shell.run("Firefox https://www.example.com=" + text1.value);
shell.run("Chrome https://www.example.com=" + text1.value);
shell.run("file:///C:\Users\*\AppData\Local\Vivaldi\Application\vivaldi.exe https://www.example.com=" + text1.value);
}
</script>
</body>
</html>
I am learning some more JavaScript and am having trouble getting a temperature conversion exercise to run.
The below is what I've written so far with the code commented out being a formula from an earlier exercise I did from my instruction book.
Here's the code:
<!--
Challenge:
Write a function to take a temperature in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Hour 2.
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
document.write ("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write ("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
</body>
</html>
-->
<html>
<head>
<script>
var cTemp =40; // temperature in Celsius
// Let's be generous with parentheses
var hTemp = ((cTemp * 9))/5 + 32;
</script>
</head>
<body>
<script>
function conversion(a, b) {
var a = 10;
var b = hTemp;
alert (conversion);
}
</script>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Right now when I run the code is displays all the code of the conversion function but doesn't actually convert!
I have been going through this for hours and I feel like the right answer isn't too far away. My question in a nutshell: What do I need to correct to get this to run properly?
Help would be appreciated as I am keen to keep coding but have hit a brick wall here.
You have written alert(conversion), which will basically display the function code, since conversion is a reference to the function.
One other thing, your conversion function takes two variables a and b which is unnecessary as you are not passing any parameters while calling it.
Here is what you can do:
<html>
<head>
<script>
function conversion() {
let cTemp =40; // temperature in Celsius
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
</script>
</head>
<body>
<input type="button" value="Click for Conversion" onclick="conversion() " />
</body>
</html>
Since you are learning, you should start using best practices. Avoid var for variable declaration and use let instead, as it is block scoped. Instead of using alert you can also use console.log to print values in developer console. I would advise you to search for some tutorials on Google Chrome Developer Tools.
There are several problems with your solution:
You are passing a function to the alert and not the result of the function.
In Javascript you can pass around functions as variables. So if you do alert(conversion), you tell the browser to show the actual function code to the user.
To execute the function, you put parantheses after the function name:
alert(conversion());
You are declaring argument for your function but not using them
Your function is
function conversion(a, b) { …
But you call the function without arguments conversion(), you could call it with arguments like this:
<input type="button" value="Click for Conversion" onclick="conversion(40,10) " />
You are overwriting your arguments without using them
But you will see that nothing changes by adding these numbers, it is because you overwrite them in your function anyway a = 10; b = hTemp. Also if you want to convert a temperature you only should have one input variable. So let us rewrite your function:
function conversion(cTemp) {
let hTemp = ((cTemp * 9))/5 + 32;
alert (hTemp);
}
So now then function accepts an argument called cTemp and then puts out the conversion. You can now call the function with different arguments like this:
<input type="button" value="Click to convert 40 C" onclick="conversion(40) " />
<input type="button" value="Click to convert 50 C" onclick="conversion(50) " />
Or even better, you can do a prompt:
function promptForConversion() {
let cTemp = prompt("Temperature in Celsius");
conversion(cTemp);
}
<input type="button" value="Click to convert number" onclick="promptForConversion(50) " />
These are very basic principles, I highly recommend to do some more tutorials, that also teach you how to organize your code in reusable functions. Good luck!
I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.
I need to retrieve URL parameters (which I can do successfully) and based on one parameter, decide which iframe src to fill, then with other parameters auto fill the form that is created via the form src. First issue is that I can't keep the page from going into an infinite loop. It loads properly and shows the right iframe, but the infinite loop (load) needs to stop. Second, I can't get the other parameters to autofill the input values.
Here is the code. I hope you can help. Here is the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC- xhtml1-200000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Keep your jQuery up to date -->
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var test = urlParams["entry"];
var test2 = urlParams["test"];
function iframedirect(){
if (test=="sldk") {
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
}
</script>
</head>
<body id="bodyId" class="mktEditable" align="center" >
<iframe id="frame1" src="" onload="iframedirect()" height="750px" width="620px" scrolling="no" frameborder="0" marginwidth="0"></iframe>
</body>
</html>
The infinite loop is probably caused by the result of the function iframedirect().It changes the src of the iframe and triggers the onload event again and again.
You could use a variable to point out if the iframe has been loaded by iframedirect().
var test = urlParams["entry"];
var test2 = urlParams["test"];
var isLoadedByIFrameDirect = false;
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "url1";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "url2";
}
isLoadedByIFrameDirect = true;
}
}
Okay, so the problem is that I created a sel-freferencing onload event. Bad idea. To solve the issue, I needed to remove the onload from the iframe element. I tried putting it in the Body before without luck. But I might have screwed it up, so don't ignore that option if you have a similar situation. I decided to do it with Javascript right after the function. If you are a novice, the difference between Javascript onload and HTML onload can be found here
W3Schools onload Event
I still have not solved the "autofilling iframe form from url parameter" portion of this problem. I will make an additional comment to this answer once I figure that out.
In any case, here is the code
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "http://na- sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
isLoadedByIFrameDirect = true;
}
}
window.onload = iframedirect;
Is it possible to pass the totalScore var to another page onclick so that it can be displayed there? ex: click submit link it goes to yourscore.html and display the score on page
$("#process").click(function() {
var totalScore = 0;
$(".targetKeep").each( function(i, tK) {
if (typeof($(tK).raty('score')) != "undefined") {
totalScore += $(tK).raty('score');
}
});
alert("Total Score = "+totalScore);
});
Let we suppose that your HTML may be as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#process").click(function() {
var totalScore = 0;
/*
Your code to calculate Total Score
Remove the next line in real code.
*/
totalScore = 55; //Remove this
alert("Total Score = "+totalScore);
$("#submit-link").attr('href',"http://example.com/yourscore.html?totalScore="+totalScore);
});
});
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="process">Process</button>
<br />
Submit Total Score
</body>
</html>
Check out this DEMO
In yourscore.html you may able to know more in the following queation to extract the URL parameter from the URL:
Parse URL with jquery/ javascript?
This is generally done by changing the url of the page. i.e. if you are going go to a new page, just do:
http://example.com/new/page?param1=test
If the page already exists in a new window (like a popup that you own), set the url to something new:
http://example.com/new/page#param
Open a window:
var win = window.open('http://example.com/new/page?totalscore'+totalscore,'window');
Change the location:
win.location.href='http://example.com/new/page?totalscore'+totalscore;
Other ways of doing this could be websockets or cookies or localstorage in HTML5.
if you are aiming to support more modern browsers the elegant solution could be to use sessionStorage or localStorage! Its extremely simple and can be cleared and set as you need it. The maximum size at the low end is 2mb but if your only storing INTs then you should be okay.
DOCS:
http://www.html5rocks.com/en/features/storage
http://dev.w3.org/html5/webstorage/
DEMO:
http://html5demos.com/storage
EXAMPLE:
addEvent(document.querySelector('#local'), 'keyup', function () {
localStorage.setItem('value', this.value);
localStorage.setItem('timestamp', (new Date()).getTime());
//GO TO YOUR NEXT PAGEHERE
});