|
|||||||
| JavaScript JavaScript (not Java) Discussion and technical support, including AJAX and frameworks (JQuery, MooTools, Prototype...) |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
making values from forms into global JS variables
Hey,
I have very basic code that I am tinkering with as I learn new JS functions or techniques etc. So far I have: Code:
<html>
<head>
<script type="text/javascript">
function validate() //validate the form1 values
{
if (isNaN(document.form1.x.value) || isNaN(document.form1.y.value) || isNaN(document.form1.z.value))
{
alert("Please enter a value for x, y and z");
}
else {
radio_selection() //call the function
}
}
</script>
<script type="text/javascript">
function radio_selection()
{
chosen = ""
len = document.form1.r1.length
//determine which radi button was checked
for (i = 0; i <len; i++) {
if (document.form1.r1[i].checked) {
chosen = document.form1.r1[i].value
}
}
if (chosen == "smallest number") {
math_smallest()
}
else if (chosen== "largest number") {
math_largest()
}
else if (chosen == "mean") {
math_mean()
}
}
</script>
<script type="text/javascript">
function math_largest()
{
a = Math.max(Number(document.form1.x.value),Number(document.form1.y.value))
b = Math.max(Number(a),Number(document.form1.z.value))
alert("The largest number of " + document.form1.x.value + ", " + document.form1.y.value + " and "+ document.form1.z.value + " is " + b);
}
</script>
<script type="text/javascript">
function math_smallest()
{
a = Math.min(Number(document.form1.x.value),Number(document.form1.y.value))
b = Math.min(Number(a),Number(document.form1.z.value))
alert("The smallest number of " + document.form1.x.value + ", " + document.form1.y.value + " and "+ document.form1.z.value + " is " + b);
}
</script>
<script type="text/javascript">
function math_mean()
{
a = (Number(document.form1.x.value) + Number(document.form1.y.value) + Number(document.form1.z.value)); // find the sum of the values
b = Number(a/3);
c = Math.round(Number(b)*100)/100; //number rounded to the two decimal places
alert("The mean of " + document.form1.x.value + ", " + document.form1.y.value + " and "+ document.form1.z.value + " is " + c);
}
</script>
</head>
<body>
<h3>Please Enter three numbers</h3>
<form name="form1">
<font>Number 1  </font><input type="text" name="x" value="x" size="5"><br />
<font>Number 2  </font><input type="text" name="y" value="y" size="5""><br />
<font>Number 3  </font><input type="text" name="z" value="z"size="5"><br /><br />
<input type="radio" name="r1" value="smallest number" onclick="validate()">Smallest Number
<input type="radio" name="r1" value="largest number" onclick="validate()">Largest Number
<input type="radio" name="r1" value="mean" onclick="validate()">The Mean
</form>
</body>
</html>
Now, I wanted to make document.form1.x.value a global variable that would be used in all the functions, rather than having to type it out long. So document.form1.x.value become x. I tried having all the functions within one script, and then adding x = document.form1.x.value for x, y and z, then followed by the functions. However, this didn't work, I just got no response when selecting a radio button. Does anyone have any ideas or helpful links to help me solve this? |
|
#2
|
||||
|
||||
|
Just need to define it early and set the value afterward:
HTML Code:
<!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> <script type="text/javascript"> var x, y, z; function validate() //validate the form1 values { if (isNaN(document.form1.x.value) || isNaN(document.form1.y.value) || isNaN(document.form1.z.value)) { alert("Please enter a value for x, y and z"); } else { x = document.form1.x.value; y = document.form1.y.value z = document.form1.z.value; radio_selection() //call the function } } function radio_selection() { chosen = "" len = document.form1.r1.length //determine which radi button was checked for (i = 0; i <len; i++) { if (document.form1.r1[i].checked) { chosen = document.form1.r1[i].value } } if (chosen == "smallest number") { math_smallest() } else if (chosen== "largest number") { math_largest() } else if (chosen == "mean") { math_mean() } } function math_largest() { a = Math.max(Number(x),Number(y)) b = Math.max(Number(a),Number(z)) alert("The largest number of " + x+ ", " + y + " and "+ z + " is " + b); } function math_smallest() { a = Math.min(Number(x),Number(y)) b = Math.min(Number(a),Number(z)) alert("The smallest number of " + x + ", " + y + " and "+ z + " is " + b); } function math_mean() { a = (Number(x) + Number(y) + Number(z)); // find the sum of the values b = Number(a/3); c = Math.round(Number(b)*100)/100; //number rounded to the two decimal places alert("The mean of " + x + ", " + y + " and "+ z + " is " + c); } </script> </head> <body> <h3>Please Enter three numbers</h3> <form name="form1"> <font>Number 1  </font><input type="text" name="x" value="x" size="5"><br /> <font>Number 2  </font><input type="text" name="y" value="y" size="5""><br /> <font>Number 3  </font><input type="text" name="z" value="z"size="5"><br /><br /> <input type="radio" name="r1" value="smallest number" onclick="validate()">Smallest Number <input type="radio" name="r1" value="largest number" onclick="validate()">Largest Number <input type="radio" name="r1" value="mean" onclick="validate()">The Mean </form> </body> </html>
__________________
54 68 65 42 65 61 72 4D 61 79 |
|
#3
|
|||
|
|||
|
Cheers, Bearmay, works a treat.
I did the same thing except I had the variables before the function. so var x var y var z function validate () can see why it didn't work now lol. Thanks!! |
|
#4
|
||||
|
||||
|
Here's a function that creates global variables with a given name:
Code:
function set_var(name, value) {
window[name] = value;
}
Code:
//validate the form1 values
function validate() {
var formEls = document.form1.elements;
if (isNaN(formEls.x.value) || isNaN(formEls.y.value) || isNaN(formEls.z.value)) {
alert("Please enter a value for x, y and z");
} else {
set_var( formEls.x.name, parseFloat(formEls.x.value) );
set_var( formEls.y.name, parseFloat(formEls.y.value) );
set_var( formEls.z.name, parseFloat(formEls.z.value) );
radio_selection() //call the function
}
}
__________________
My Blog: FundaMental Disaster Accessible DHTML Tabs | Quick CSS Positioning Explanation | Quick Floated Elements Explanation | 50% + 50% != 100% | Gaps Under Images | ID vs. Class | Gappy Lists in Internet Explorer | Why Tables Are Slower | Benefits of XHTML vs. HTML | Linking to External Style Sheets | About DOCTYPES | Web Design is a Peanut Butter & Jelly Sandwhich | CSS: To Hack Or Not To Hack | Internet Explorer and Transparent PNGs |
|
#5
|
|||
|
|||
|
Thanks toicontien, or is it toicantien? lol. I will keep hold of that script for future use if you don't mind.
the variables were numbers, I used Number() to make sure they were handled as such. thanks, Mike |
|
#6
|
||||
|
||||
|
Actually, you really need to use the parseFloat function. The isNaN function is the compliment to parseFloat and parseInt. I wrote a blog post about numbers and strings in JavaScript that might be a good read: A Practical Guide To Numbers in JavaScript
__________________
My Blog: FundaMental Disaster Accessible DHTML Tabs | Quick CSS Positioning Explanation | Quick Floated Elements Explanation | 50% + 50% != 100% | Gaps Under Images | ID vs. Class | Gappy Lists in Internet Explorer | Why Tables Are Slower | Benefits of XHTML vs. HTML | Linking to External Style Sheets | About DOCTYPES | Web Design is a Peanut Butter & Jelly Sandwhich | CSS: To Hack Or Not To Hack | Internet Explorer and Transparent PNGs |
|
#7
|
||||
|
||||
|
Um... sorry, toicontien, but I disagree with basically everything in your post here and the basic assumptions in your blog post.
Quote:
Quote:
Computers require very specific input, and if the user doesn't do that, then, rather than fudging it, I think it's better to just alert the user that they made a mistake, remind them how to do it correctly, and have them try again.
__________________
for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"')) {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n"; |
|
#8
|
||||
|
||||
|
Quote:
Quote:
I also originally thought the isNaN function was the compliment to parseFloat and parseInt, but now realize it isn't. It is, in fact, the complimentary function to Number. So a couple things to ammend on my blog post: 1) A number literal is a primitive data type. 2) A number variable is an object, whose constructor is Number 3) The isNaN function is the compliment of Number, not parseFloat and parseInt.
__________________
My Blog: FundaMental Disaster Accessible DHTML Tabs | Quick CSS Positioning Explanation | Quick Floated Elements Explanation | 50% + 50% != 100% | Gaps Under Images | ID vs. Class | Gappy Lists in Internet Explorer | Why Tables Are Slower | Benefits of XHTML vs. HTML | Linking to External Style Sheets | About DOCTYPES | Web Design is a Peanut Butter & Jelly Sandwhich | CSS: To Hack Or Not To Hack | Internet Explorer and Transparent PNGs |
|
#9
|
||||
|
||||
|
Quote:
var x = 4; var y = new Number(4); alert(typeof x); // number alert(typeof y); // object Quote:
Quote:
__________________
for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"')) {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n"; Last edited by Jeff Mott; 01-16-2008 at 01:44 PM. |
|
#10
|
||||
|
||||
|
Quote:
Code:
var x = 4.546851; alert(x.toFixed(3)); Code:
function getType(x) {
var type = "unknown";
if (x.constructor) {
switch (x.constructor) {
case Number: type = "number"; break;
case String: type = "string"; break;
case Array: type = "array"; break;
case Object: type = "object"; break;
case Function: type = "function"; break;
default: type = typeof(x); break;
}
} else {
type = typeof(x);
}
return type;
}
Quote:
Quote:
Code:
var x = "4.7a"; var y = "3.2"; alert(isNaN(x) + "\n" + isNaN(y)); // Alerts true and false alert(Number(x) + "\n" + parseFloat(x)) // Alerts NaN and 4.7 1) Use a strict test like isNaN and convert strings to numbers using the Number function. 2) Strip out non numeric characters from the string, then pass it to the Number, parseFloat or parseInt functions to convert the string to a number. Method 1 is the strictest, and any non numeric input would generate an error, and it would force the user to only enter valid numeric characters. This is the programmer friendly method. Method 2 is the least strict and offers some error correction. This error correction, as Jeff mentioned earlier, could introduce an incorrect value to your program, but not an incorrect data type. If using method 2, which is the most user friendly, make sure your program checks the input to make sure it's a valid value. This is the user friendly method, as it provides some simple error correction. In either case, you've got to check for a valid value, then alert the user and give them a chance to correct their mistake. For instance, if your script requires a number 10 or less, you still need to check that value regardless of whether or not use use Number, parseFloat or parseInt to convert the string to a number. When converting strings to numbers, you can use two basic work flows: A) Test first, then convert A.1) Test the string with isNaN. If true is returned, alert the user to correct the error. A.2) If isNaN returns false, convert the string to a number using the Number function. B) Convert, then test B.1) Convert the string to a number using Number, parseFloat or parseInt. B.2) Test the resulting value with isNaN. If true is returned, alert the user and allow them to correct their error. Just out of curiosity Jeff, which method do you use? And I realize the two methods above are pretty generalized. I use both methods intermittently. Good discussion, however off topic it may have become. I'm learning more with each post.
__________________
My Blog: FundaMental Disaster Accessible DHTML Tabs | Quick CSS Positioning Explanation | Quick Floated Elements Explanation | 50% + 50% != 100% | Gaps Under Images | ID vs. Class | Gappy Lists in Internet Explorer | Why Tables Are Slower | Benefits of XHTML vs. HTML | Linking to External Style Sheets | About DOCTYPES | Web Design is a Peanut Butter & Jelly Sandwhich | CSS: To Hack Or Not To Hack | Internet Explorer and Transparent PNGs |
|
#11
|
|||||||
|
|||||||
|
Quote:
I tried to find the docs for you where I read it. So far I've found the behavior described for strings but not yet for numbers (http://developer.mozilla.org/en/docs...tring_Objects). I'll keep looking. In the mean time, here's the described behavior of calling String methods on a string literal: Quote:
Quote:
Quote:
Quote:
Quote:
I also prefer method 1 not just as a programmer but also as a user. I've used software before where my typos are silently ignored and changed to something else. And then when the program doesn't work like it's supposed to, I don't have any idea why because I'm not even aware that I made a mistake. I end up wasting time double and triple checking my settings until I finally spot the bad value. So however you approach it, I think method 2 is just bad practice. Quote:
Code:
var someNumberEntry = Number( document.getElementById("someFormCtrl").value );
if (isNaN(someNumberEntry )) {
// some kind of alert, perhaps jump to the form control and highlight in red
// might stop processing here also if further calculations depend on someNumberEntry
}
__________________
for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"')) {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n"; |
|
#12
|
||||
|
||||
|
Quote:
![]() The article you linked to described some functional differences between string literals and string objects. I wonder if we can find anything like that with numbers. Quote:
Code:
/* In C++ */ int x = 10; /* I don't believe you can do x.anything. The variable x is simply a variable. */ Code:
/* In JavaScript */ var x = 10; y = x.toString(); ![]() Quote:
Quote:
I wonder if there are any performance differences between number literals and number objects? It'd be cool to know if using new Number() over assigning a number to a variable has any benefits. If you were going to call a Number class method repeatedly on a variable, I wonder if you'd get better performance by creating a number object to begin with, rather than relying on JavaScript to temporarily convert a number literal to an object repeatedly.
__________________
My Blog: FundaMental Disaster Accessible DHTML Tabs | Quick CSS Positioning Explanation | Quick Floated Elements Explanation | 50% + 50% != 100% | Gaps Under Images | ID vs. Class | Gappy Lists in Internet Explorer | Why Tables Are Slower | Benefits of XHTML vs. HTML | Linking to External Style Sheets | About DOCTYPES | Web Design is a Peanut Butter & Jelly Sandwhich | CSS: To Hack Or Not To Hack | Internet Explorer and Transparent PNGs |
|
#13
|
||||
|
||||
|
Quote:
__________________
for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"')) {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n"; |
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|