Forum Moderators: open
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>
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>