Reputation: 825
I'm following the answer from add onclick function to a submit button
Here's my HTML:
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
and JS:
var text = document.getElementById("name").value;
function process() {
alert(text);
return true;
}
When I click the form, it says: Uncaught ReferenceError: process is not defined
I have double checked everything, and the process()
function is already defined. I wonder why this doesn't work
Here's the DEMO
==================UPDATE================================
I tried it using SO's code snippet, and it worked. I guess there's something wrong with jsfiddle, somehow the javascript and HTML are not conected
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
Upvotes: 0
Views: 2014
Reputation: 201548
The error message you get is due to the way Jsfiddle.net works. Tested in isolation, the code runs without errors. However, the alerted text is the empty string. The reason is that the variable text
is assigned only once, at the start of execution, and then the input field is empty.
One way to fix this is to make the text
variable local to the function, so that it will be assigned a value whenever the function is invoked:
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}
Upvotes: 1
Reputation: 2794
The problem is your order of actions. Your javascript needs to be appended after the DOM loads.
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
<script>
var text = document.getElementById("name").value;
function process() {
alert(text);
return true;
}
</script>
And you should actually include var text within the function then you can load the JS wherever.
Name: <input type="text" id="name">
<br>
<br>
<input type="submit" onclick="return process();" />
<script>
function process() {
var text = document.getElementById("name").value;
alert(text);
return true;
}
</script>
Upvotes: 2