Forum Moderators: open

Message Too Old, No Replies

Not Reading Global Variables

         

Jeremy_H

10:06 pm on Jul 14, 2006 (gmt 0)

10+ Year Member



OK, I have no clue what I'm doing wrong.

I thought I was setting up my global variables correctly, but if you type in a value into the input, and click somewhere else on the page (to blur it) it gives me undefined results.

It would seam that the first test would output what the user typed in the box. Comes back as undefined.

The second test alert should output "Second Check Works", but it doesnt.

And finally, the third alert works for me.

Any advice would be greatly appreciated.

<html>
<head>
<script type="text/javascript">

var v1=document.t.v1.value;
var check2="Second Check Works";

function checker(){
alert(v1);
alert(check2);
alert("Third Check Works.");
}

</script>

</head>
<body>

<form id="t" name="t">
<input type="text" id="v1" name="v1" onBlur="return checker();">
</form>

</body>
</html>

kaled

11:17 pm on Jul 14, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Javascript code that is not wrapped in a function executes immediately. Since this code is in the head, it cannot refer to objects that don't yet exist.

The simplest solution would be to put the <script> at the end of the <body> (i.e. after the objects that are referred to).

Kaled.

rocknbil

4:34 am on Jul 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Also it's dangerous to name a variable the same as a form object. (v1)

If I'm gathering the task correctly, why do you need to declare these as globals? Then you'd have to declare a new var for every object you want to run through checker. Below is an approach for three types of form objects.

<html>
<head>
<script type="text/javascript">
function checker(obj){
var val = ''; // this avoids undefined
if (obj.type=='select-one') {
var ind=obj.selectedIndex;
val = obj[ind].value;
}
else { val = obj.value; }
val=(val!= '')?val:'Value is blank';
alert(val);
}

</script>
</head>
<body>
<form id="t" name="t">
<input type="text" id="v1" name="v1" onBlur="return checker(this);">
<select name="v2" id="v2" onBlur="return checker(this);">
<option value="">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<textarea name="v3" id="v3" onBlur="return checker(this);"></textarea>
</form>
</body>
</html>