I’m starting in JS and have been having trouble with a particular function I’m trying to write. The purpose is to have the text change once the button is pressed. The “nothing” text should change into “You say hi, I say Hey?” With the Hey? being text already on the document.
Here’s the code, any pointers would be welcome!
<html>
<head>
<title>Javascript test </title>
</head>
<body>
<p id="hey">Hey?</p>
<p id ="nothing">Nothing</p>
<INPUT type =button VALUE="Button?" OnClick=(take())>
<script>
function take(){
var hey=document.getElementById("hey");
var nothing =document.getElementById("one");
nothing.appendChild(document.createTextNode("You say hi, I say " + hey));
}
</script>
</body>
</html>
Alright, thanks for all the help guys. No one in particular was 100% right but i tried a combination of all the suggestions and got about 99% of the way to where i wanted to go. My code looks like this now. The last change im trying to make is not to append new text strings but to replace the old string with the string that is currently being appended.
<html>
<head>
<title>Javascript test </title>
</head>
<body>
<p id="hey">Hey?</p>
<p id ="nothing">Nothing</p>
<input type ="button" value="Button?" OnClick="take();"/>
<script>
function take(){
var hey=document.getElementById("hey");
var nothing =document.getElementById("nothing");
nothing.appendChild(document.createTextNode("You say hi, I say " + hey.innerHTML));
}
</script>
</body>
</html>
I appreciate the help, thank you Stack Overflow community!
Your code has a few issues.
First, you should specify
type="text/javascript"on your script tag.Second, your input should look like this:
Third, you should bind your event handler in the script tag (See SoC):
Fourth, your function looks for an element with id
one, which does not exist. Did you mean idnothinginstead?Fifth, assuming you use the correct id to get the
nothingelement, you need to use the value from the otherpwhen setting the value.See a working example here: http://jsfiddle.net/M5UWn/
As a side note, I found jQFundamentals an excellent learning site for both jQuery and native javascript.