Forum Moderators: open

Message Too Old, No Replies

help writing script

         

phoenix1215

12:36 am on Feb 23, 2007 (gmt 0)

10+ Year Member



I'm trying to write a script that will calculate the moon's phase based on the entered value for the position and then using basic math functions

here's what I know....

each member has a different position for the moon, they view the source code and find the number value for the position, they then enter it into the input box on my forum

if the number is >=180, it then subtracts 157.5 and divides by 22.5 then rounds the number up or down automatically

if the number is <180, it then adds 202.5 and divides by 22.5 then rounds the number up or down automatically

I've posted this on tons of other forums and only one person has tried to help

he gave me this code:

function calculate(position) {
var phase;
position = parseFloat(position);
if (position > 180) {
phase = Math.round((position - 157.5) / 22.5);
provideAnswer(phase);
}
else if (position < 180) {
phase = Math.round((position - 202.5) / 22.5);
provideAnswer(phase);
}
else {
var text = document.createTextNode("You must enter a number!");
document.getElementsByTagName("div")[0].appendChild(text);
}
}

function provideAnswer(phase) {
// Do Something
}


and then the html code was:
<div>
<input type="text" id="position">
<input type="submit" onclick="calculate('position');">
</div>

but when I tried that it only wrote You must enter a number! over and over again... then he wrote back that the code was wrong:
calculate('position') should be calculate(document.getElementById('position').value)

there are 2 instances of this: one in the javascript and one in the html coding, but no matter what that just completely disabled the whole thing....

I'm lost, help please?

cmarshall

12:06 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
// <![CDATA[
function calculate(position) {
var phase;
position = parseFloat(position);
if (position > 180) {
phase = Math.round((position - 157.5) / 22.5);
provideAnswer(phase);
}
else if (position < 180) {
phase = Math.round((position - 202.5) / 22.5);
provideAnswer(phase);
}
else {
var text = document.createTextNode("You must enter a number!");
document.getElementsByTagName("div")[0].appendChild(text);
}
}

function provideAnswer(phase){
alert(phase);
}
// ]]>
</script>
</head>
<body>
<div>
<form action="#">
<input type="text" id="position">
<input type="submit" onclick="calculate(getElementById('position').value);">
</form>
</div>
</body>
</html>

1) He was right, but not completely. You also need to get the value from the element, as that is what you were expecting in the function parameter.

2) You should always wrap form elements in a form, even if it isn't necessary to have a form.

birdbrain

12:37 pm on Feb 23, 2007 (gmt 0)



Hi there phoenix1215,

and a warm welcome to these forums. ;)

I have just done this similar example, so I might as well post it too...


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style type="text/css">
#container {
width:150px;
padding:20px;
border:3px double #999;
background-color:#f3f3f3;
color:#666;
margin:auto
}
#container div {
margin-bottom:6px;
}
</style>

<script type="text/javascript">

var df=document.forms;

window.onload=function() {
df[0][0].focus();
df[0][2].onclick=moonphase;
df[0][3].onclick=init;
}

function moonphase() {
num=parseFloat(df[0][0].value);
if((isNaN(num))¦¦(num>360)¦¦(num<0)) {
alert('Please enter a value between 0 and 360 ');
df[0].reset();
df[0][0].focus();
return;
}
if(num>=180){
num=Math.round((num-157.5)/22.5);
}
else{
if(num<180){
num=Math.round((num+202.5)/22.5);
}
}
df[0][1].value=num;
}

function init() {
df[0][0].focus();
}
</script>

</head>
<body>

<form action="#">
<div id="container">
<div><input type="text" size="2"/><label> : position</label></div>
<div><input type="text" size="2"/><label> : phase</label></div>
<input type="button" value="calculate"/>
<input type="reset" value="reset"/>
</div>
</form>

</body>
</html>


Note:- the ¦¦ for some strange reason peculiar to this forum - (and it has other idiosyncrasies :) ) appear as broken lines instead of solid.
This, of course, makes it extremely difficult to post code that will actually work.

birdbrain

cmarshall

12:55 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<form action="#" onsubmit="calculate(getElementById('position').value);"><div>
<input type="text" id="position">
<input type="submit" onclick="calculate(getElementById('position').value);">
</div></form>

My bad.

In XHTML 1.1, you need to have a block element inside of a <form>, as a <form> is "formless." ;)

I would also add an onsubmit handler to the <form>, so you get return keys.

s_mk

1:56 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



Honestly, I have given up on form tags. Especially for cases like this where you aren't even submitting a form at all, and you are relying on javascript to be enabled anyway..

<form action="#" onsubmit="calculate(getElementById('position').value);"><div>
<input type="text" id="position">
<input type="submit" onclick="calculate(getElementById('position').value);">
</div></form>

Why not forget the extra steps an just:


<input type="button" value='calculate onclick="calculate(getElementById('position').value);">

for cases where you are submitting a form. just create the form via DOM, and just append the elements as you run through your form validation. Then use the formNode.submit(). Although not infallible, this has helped me avoid most form bots from finding the action as I set it with formNode.action = 'myurl.html'.

Just a suggestion.

Fotiman

2:13 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Technically speaking, I don't believe it's valid to have form inputs without a <form> wrapped around them.

s_mk

2:22 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



I don't believe it's valid to have form inputs without a <form> wrapped around them.

..not sure what you mean by valid,

but I have yet to find a javascript enabled browser that it wont work for. It even works on Safari...

cmarshall

3:50 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It even works on Safari.

Believe it or not, Safari is one of the only browsers out there that supports the standards properly. It used to be the only one, but I think Mozilla/Gecko caught up. I can't remember the test, but someone came up with this brutal litmus test (I think the W3C), and Safari was the only one that passed.

I have had this bite me before. I don't remember exactly what browser it was (maybe Mac IE -always a barrel of monkeys). If I didn't have the elements wrapped, they were not displayed properly.

s_mk

4:01 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



you mean [webstandards.org ]
?

I think we are all breathing a sigh of relief now that IE/MAC is finally dead.

Fotiman

4:03 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month





I don't believe it's valid to have form inputs without a <form> wrapped around them.

..not sure what you mean by valid,

I'm referring to valid HTML... that is, HTML that is properly formatted and validates according to the HTML spec. Here's a validator:
[validator.w3.org...]


but I have yet to find a javascript enabled browser that it wont work for. It even works on Safari...

Right, most browsers will still "guess" at what you intended with your invalid code. But it is just that... a guess. If you write your code to the HTML standards, you will save yourself many headaches.

cmarshall

4:54 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



you mean [webstandards.org ]?

That's one of them. There was another one that was for more than CSS. It exercised the [X]HTML elements and JavaScript as well.

I think we are all breathing a sigh of relief now that IE/MAC is finally dead.

I think we need to drive a stake through it, cut off it's head, jam silver spikes into its eyes and bury it at a crossroads.

However, I use it as one of my abuse test browsers (I also use Opera 6). If I can make a site render on it, the site will render pretty much anywhere.

s_mk

5:34 pm on Feb 23, 2007 (gmt 0)

10+ Year Member




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>title</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
<input type='text' id='textinp' name='textinp' />
</body>
</html>

validates fine at [validator.w3.org...]

yes, obviously if submitting the elements as not part of the form, im sure you will run into trouble. What I'm saying is do this:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language="Javascript" type="text/javascript" src="myJSLib.js"></script>
<title>title</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
<input type='text' id='textinp' name='textinp' />
<input type='button' value='sendit' onclick='vCheck() />
</body>
</html>

// js
vfunction vCheck(){
var tInput = document.getElementById('textinp');
if(tInput)var val = tInput.value;
if(val) && typeof(val) == 'string' && val.length < 101 && val.length){
/* create a form */
var fNode = document.createElement('form');
/* create the attributes needed */
fNode.action = 'myUrl.php';
fNode.method = 'POST';
/* add the elements */
fNode.appendChild(tInput);
/* add it to the body */
var bds = document.getElementsByTagName('body');
bds[0].appendChild(fNode);
/* submit */
fNode.submit();
}

I think the only good thing about the form element is the elements array, but there is little advantage to it unless you have a quantity of elements that will run through the same validation rules. If they all validate with different rules, you're going to have to cycle through them 1 by one based on Id anyway.

The advantage of this is that you keep the action out of the html page, and you are reasonably sure that you aren't submitting anything you don't want, or don't need. and you can use fields for several forms on the same page by assembling them in different form packages.

It's just what I've found to be helpful, I'm sure there are plenty of ways to do this.

next is a speech, that is probably uncalled for in reference to this thread, but I had to vent it, so feel free to skip reading it...

As far as standards compatibility goes, the standards compatible browsers (Opera, and Safari) result in a cumulative 3.2 percent of users [w3schools.com ] and the majority: (IE - 58.6% & Firefox 31%) still falling pretty short on on standards compatibility (the former seemingly striving to be incompatible :S ), Can those of us who have to do this for a living even consider the W3C standards as just that, standards?

I mean really, Microsoft was ON THE COMMITTEE for developing a standardized event model, and then completely disregarded their own committee's resolution, and implemented their own POS event model for reasons I can only infer were to maintain their hold on the browser market share.

Anyway, what I'm trying to say is that I pray for the day when there is a set of standards we can all adhere to, as thats the day my job will become exponentially easier, but with the browser companies ignoring the rules, I consider anything that works for my project's target browser list to be standardized.

Sorry to flame, but RFCs are easily implemented for almost every other protocol, yet we have been waiting on a standards compliant browser market since the 80s. Thin clients are the way of the future, and it's about time they all got on board..

-Greg

cmarshall

6:40 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I write standards-compliant code for a number of reasons:

1) It turns the validator into a debugger. Whenever I have a validation failure, I have a bug. HUGE time saver. HUGE.

2) It's like whizzing in a dark suit. No one else knows, but I feel warm inside.

3) I am a contrarian by nature. After everyone started complaining about how impossible it was to write standards-compliant code and have attractive and lively sites, I took that as a challenge. I write attractive and lively sites that adhere to standards.

4) It makes it easier to validate my pages for accessibility. Most accessibility checks puke immediately when they hit validation errors (or they did).

5) It has become habit. I don't even give it a second thought nowadays.

Fotiman

6:54 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



But this does NOT validate:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Language" content="en" >
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>title</title>
</head>
<body >
<input type='text' id='textinp' name='textinp'>
</body>
</html>

With regards to the rest of you post:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

You should read the thread: Why most of us should NOT use XHTML [webmasterworld.com]


<script language="Javascript"

You should omit the language attribute. It's not valid and not needed.


<body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">

YUCK! Welcome to the year 1990! All those presentational attributes should be replaced with CSS.

Also, requiring JavaScript in order to submit a form is not good.


The advantage of this is that you keep the action out of the html page, and you are reasonably sure that you aren't submitting anything you don't want, or don't need. and you can use fields for several forms on the same page by assembling them in different form packages.

The disadvantage is that it's totally inaccessible for anyone that doesn't have JavaScript, and you lose certain accessiblity functionality (like a default submit key) when you don't include a real submit button.

As for your rant, I'm not sure why you think Firefox is not standards compliant. I write all of my pages to work correctly in standards compliant browsers and then include fixes as needed for IE. While I agree that current standards and their implementations may be lacking somewhat, I definately have a more optimistic approach to developing to standards than you do. I know it has certainly made my life easier.

[edited by: Fotiman at 6:55 pm (utc) on Feb. 23, 2007]

s_mk

6:55 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



After everyone started complaining about how impossible it was to write standards-compliant code and have attractive and lively sites, I took that as a challenge. I write attractive and lively sites that adhere to standard

Can I have a look at some examples? I would love to be able to write only w3c code.

thanks
-Greg

cmarshall

7:53 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Can I have a look at some examples?

Ask, and ye shall receive. Check your SM.

-Chris

cmarshall

2:15 pm on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Oh, yeah. One example of valid code that I can post here.

I was actually shocked to find that this [msn.com] site validates XHTML 1.0 Strict [validator.w3.org].