0

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?

Popa Gabriel
  • 31
  • 1
  • 9

1 Answers1

2

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

j08691
  • 204,283
  • 31
  • 260
  • 272
  • @Shashank - Maybe this will help clear it up: "An important point about the open() method is that it is almost always invoked as window.open(), even though window refers to the global object and should therefore be entirely optional. Since the document object also has an open() method, specifying the window object when we want to open a new window is essential for clarity. In event handlers, you must specify window.open() instead of simply using open(). Due to the scoping of static objects in JavaScript, a call to open() without specifying an object name is equivalent to document.open()." – j08691 May 12 '15 at 19:34
  • Source: http://www.webreference.com/js/tips/000423.html. See also http://stackoverflow.com/questions/9966182/what-is-the-difference-between-open-and-window-open-in-firefox – j08691 May 12 '15 at 19:34