Make a simple calculator?

Have to make a calculator to calculate wallpaper sizes and cost (college course so not for the ‘real world’ so doesnt need a great deal of functionality. Do i make a form in html and then name each cell? what then? Lost as hell here and been watching countless tutorials for js, need guidance i think now.

Alan

You use events.

Have a form button called “Calculate”, and use scripting to attach an onclick event to that button.
That button can then use this.form to gain a reference to the form, and from there you can use the elements collection to easily refer to the named form fields.

For example, here’s a form to calculate BMI:


<form id="calculatebmi">
    <p><label>Height (metres): <input name="height"></label></p>
    <p><label>Weight (kilos): <input name="weight"></label></p>
    <p><input name="calculate" type="button" value="Calculate BMI"></p>
    <p>Calculated BMI: <input name="bmi"></p>
</form>

Now we use the form identifier to reference the form, and from there use the elements collection of that form to get to the element we need. In this case, the calculate button.

Please note: We put scripts at the bottom, just before the </body> tag, to achieve several benefits, among which are faster page loading and no need to wait for the page to be loaded before working with page elements.


var form = document.getElementById('calculatebmi');
form.elements.calculate.onclick = calculateBMI;

The calculateBMI() function will use this.form to gain a reference to the form, so that the other values can then be retrieved. All form values are strings, so it’s a good idea to convert them to numbers when you retrieve them. If you don’t, then “1”+“1” will equal “11”


function calculateBMI() {
    var form = this.form,
        height = Number(form.elements.height.value),
        weight = Number(form.elements.weight.value),
        bmi;

    ...
}

After which you can perform sanity checks, if needed, and carry on with what needs to be done.


function calculateBMI() {
    ...

    if (!height || !weight) {
        alert('Please enter a valid height and weight.');
        return;
    }
    bmi = weight / (height * height);
    bmi = Math.round(bmi * 100) / 100;
    form.elements.bmi.value = bmi;
}

The details will differ for you of course, but those are the fundamental general principles involved.

Many many thanks! I shall try to implement this right now!

One more question, asked this on another question but didnt get any response so thought id try again -well i asked similar anyway.

To access this calculator, the assignment requires that someone needs an email and password verification. I did initially think about a prompt box in the head of the calculator page, but is this the best way to go about it? I have now 3 pages, intro, calculator (done soon fingers crossed!) and another page, should i put the verification on the intro page? as some sort of prompt box? if so do i verify what is in the box then it takes the user straight to the next page? or if incorrect remain on this page? or is it done on the calculator page?

(from a begging unorganised student!))

Many thanks for help so far again

Alan

A PHP script or other server-side solution will be best suited for that.

JavaScript is the worst thing in the world to use to authenticate users and passwords. Anyone asking you to use JavaScript to authenticate users is only giving you a rope to hang yourself with.

Hi tried that calculator but having some problems, need to get my head around it but ill be here all day doing it anyway grr

And sorry the verification thing has to be done in javascript. It is a bit of a crazy course really. I asked once why we are doing something in a certain way as there are so many other options for an easier life AND more search engine friendly. I was told it was needed as it is on the curriculum. It was around then that i decided to wind my neck in and just try and get this qualification…

Anyway yes email and password verification to access the calculator is what is needed, either from the first page or from a pop up of some sort. Any suggestions?

Thanks

Alan

Not from me :slight_smile:

Though you require it for your course, I won’t help anyone shoot themself in the neck. It’s just not right.

lol ok well thanks for the pointers so far and yes it has to be javascript to do the verification. Anyone else help here??

With regards to the calc code you posted, I thought i was doing something wrong or worked it out wrong, so i tried copying and pasting your code and seeing if the BMI calc works, but id doesnt seem to? have you just gave me parts of the code for guidance, or is this the complete code for a working calculator?

Many thanks

Alan

That’s the complete code. If you’re having trouble, post a link to a test page, or compress and attach to your post, and we’ll help you work out here the problem lies.

How do i post a test page?

<script type=“text/javascript”>
var form = document.getElementById(‘calculatebmi’);
form.elements.calculate.onclick = calculateBMI;
function calculateBMI() {
var form = this.form,
height = Number(form.elements.height.value),
weight = Number(form.elements.weight.value),
bmi;

	if (!height || !weight) {
    alert('Please enter a valid height and weight.');
    return;
}
bmi = weight / (height * height);
bmi = Math.round(bmi * 100) / 100;
form.elements.bmi.value = bmi;

</script>

<body>
<h1 align=“center”>THE WALLPAPER CENTRE</h1>

<form id=“calculatebmi”>
<p><label>Height (metres): <input name=“height”></label></p>
<p><label>Weight (kilos): <input name=“weight”></label></p>
<p><input name=“calculate” type=“button” value=“Calculate BMI”></p>
<p>Calculated BMI: <input name=“bmi”></p>
</form>

here is a copy of the code i have there, basically a copy of yours put together?

Alan

Thanks for that.

Go back to post #2 and reread the part that starts with: “Please note:”

<!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>
<link rel=“stylesheet” type = “text/css” href=“wpcss.css”>
<script type =“text/javascript” src=“wallpaper.js”>;</script>

&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;title&gt;Wallpaper Calculator&lt;/title&gt;
&lt;table border="1" align="center"&gt;
	&lt;tr&gt;
	&lt;td&gt;&lt;a href="wpsitehome.html"&gt;Homepage&lt;/a&gt;&lt;/td&gt;
	&lt;td&gt;&lt;a href="calculator.html"&gt;Calculator&lt;/a&gt;&lt;/td&gt;
	&lt;td&gt;&lt;a href="suppliers.html"&gt;Suppliers&lt;/a&gt;&lt;/td&gt;

< /tr>
</table>
</head>

<body>
<h1 align=“center”>THE WALLPAPER CENTRE</h1>

&lt;a href = "http://www.t-mobile.co.uk"
	onmouseover="document.images.tmobile.src='tmobile2.jpg';"
	onmouseout="document.images.tmobile.src='tmobile1.jpg';"&gt;
	&lt;img src="tmobile1.jpg" border="0" name="tmobile"/&gt;&lt;/a&gt;

&lt;a href = "http://www.o2.co.uk"
	onmouseover="document.images.o2.src='o22.jpg';"
	onmouseout="document.images.o2.src='o21.jpg';"&gt;
	&lt;img src="o21.jpg" border="0" name="o2"/&gt;&lt;/a&gt;

&lt;a href="http://orange.co.uk" 
	onmouseover="document.images.orange.src='orange2.jpg';" 
	onmouseout="document.images.orange.src='orange1.jpg';" &gt;
	&lt;img src="orange1.jpg" border ="0" name="orange"/&gt;&lt;/a&gt; 

&lt;a href="http://www.vodafone.co.uk/personal/index.htm"
	onmouseover="document.images.vodafone.src='vodafone2.jpg';"
	onmouseout="document.images.vodafone.src='vodafone1.jpg';"&gt;
	&lt;img src="vodafone1.jpg" border="0" name="vodafone"/&gt;&lt;/a&gt;
	
	&lt;form id="calculatebmi"&gt;
	
		&lt;p&gt;&lt;label&gt;Height (metres): &lt;input name="height"&gt;&lt;/label&gt;&lt;/p&gt;
		&lt;p&gt;&lt;label&gt;Weight (kilos): &lt;input name="weight"&gt;&lt;/label&gt;&lt;/p&gt;
		&lt;p&gt;&lt;input name="calculate" type="button" value="Calculate BMI"&gt;&lt;/p&gt;
		&lt;p&gt;Calculated BMI: &lt;input name="bmi"&gt;&lt;/p&gt;
	&lt;/form&gt;
	
	&lt;script type="text/javascript"&gt;
		var form = document.getElementById('calculatebmi');
		form.elements.calculate.onclick = calculateBMI;
		function calculateBMI() {
		var form = this.form,
		height = Number(form.elements.height.value),
		weight = Number(form.elements.weight.value),
		bmi;
		if (!height || !weight) {
			alert('Please enter a valid height and weight.');
			return;
			}			
		bmi = weight / (height * height);
		bmi = Math.round(bmi * 100) / 100;
		form.elements.bmi.value = bmi;
	&lt;/script&gt;

</body>

</html>

This? do you mean the bit where you say put the script at the bottom, just before the </body> ?

Sorry about this, im sure you can see from my line of questioning that this really isnt my forte, although ive got a bad feeling that it is going to be by the end of the year.

Thanks again

Alan

You have also missed out the closing brace for the function.

A simple way to make the calculator password protected is to add HTTP Authentication to the page with .htaccess & .htpasswd

He’s not allowed to do it the right way though, because his course instructor requires him to do it only with JavaScript.

Cheers for all your help here Paul. And yes Javascript is needed for rollover links, email and password verification and the calculator.

So how will you be encoding the passwords - with a salted hash of some kind?

You don’t want to write this kind of code:

if (email === 'paul@site.com' && password === 'mypassword') {

Because anyone loading the web page can view that javascript code, and easily work out which password to use for what email.

I have honestly not a clue how i will be doing the code as of yet. Basically family circumstances led me to missing a great portion of the course, but the course tutor has let me remain as long as i get in the assignments and pass them. Never done anything computer related before, so new to JS or any other type of programming It is a creative front end course so a lot is ok, but the javascript aspect - well ive been literally trying this since thurs now, so 4 days, and that is what has led me to asking for help in forums. Not a clue what im doing really, as long as i can work out how to do the minimum requirements ill be more than happy. the min is rollover links (managed that one), email and password verification, and calculator, cant even seem to work out the calculator to do a simple calculation with option of metric or imperial. Oh and a choice for the user to change colour and remain throughout the site. 4 days and my head is truly sozzled!! So any takers to these tasks, im all ears.
Sorry if tone sounds like that of a beaten man, but im feeling like it a bit!

Alan

Ok back for another stab! Ive done some code to validate email, only working on the @ and . parts but hey that is all the guidelines ask. The password part i was thinking of validating that they type in ‘123’ and anything else will be wrong. Here is the script i have at the minute.

<script type=“text/javascript”>
function validateForm()
{
var x=document.forms[“myForm”][“email”].value
var y=document.forms[“myForm”][“password”].value

var atpos=x.indexOf(“@”);
var dotpos=x.lastIndexOf(“.”);
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length ||“y”!=123)

{
alert(“Not a valid e-mail address”);
return false;
}

{alert"not a valid password};
return false
}
</script>

||“y”!=123 - without this bit the email verification works ‘fine’ - fine enough for this project anyway. Any suggestions on what to add or where to make it possible for the password to be 123 and anything else would be incorrect? Im sure it will be smackingly obvious to someone, but ive tried a few variations without success.

Many thanks

Alan