Popa Gabriel
Popa Gabriel

Reputation: 31

Simple age JS form doesn't work

I'm new to JavaScript and I'm making an exercise about content getting from html form. I din't want to mame a date picker. Just the checking. Here is some code:

<html>

<title>JavaScript example</title>

<script type="text/javascript">

function onload() { 

var age = document.getElementById('v').value;
var res = (age >= 18) ? "Adult" : "Minor";


}
function open(){

alert(res);
}
</script>

<body onload="onload();">
<input type="text" name="AREA" value="" id="v"/>
<input type="button" value="click" onclick="open();"/>
</body>

</html>

My html works fine, but when I'm clicking the button all the page goes blank and nothing. Some help?

Upvotes: 0

Views: 53

Answers (1)

j08691
j08691

Reputation: 207900

You have two issues:

  1. As others have noted, since you defined your res variable in your onload function it's local to that function, and your open function can't see it.
  2. The other issue, which is causing the page to go blank is the use of the name open for your function. JavaScript has a document.open function and when you click your button, you're calling it. I'd rename your function to something else to prevent that.

And as a final note, you probably don't want to run your first function onload, as the input won't have a value yet. jsFiddle example

Upvotes: 2

Related Questions