3

I am very new to javascript and I was trying to populate a textbox from html with javascript but for some reason isn't working. This is what I have:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Relations</title>
  <link rel="stylesheet" href="kandi.css" type="text/css" media="screen">
  
  <script src="myscript.js"></script>
  
  <body>
	<h1 align="center" style="font-family:Arial;" >RELATION TAGGING </h1>
	<textarea id="your_textarea" rows="15" cols="160">
	</textarea>
  
  </body>
  </head>
</html>

Javascript:

var textarea = document.getElementById("your_textarea");
textarea.innerHTML = "testing123";
4
  • try with textarea.innerHTML = ''testing123"; Commented Oct 17, 2018 at 7:59
  • Does it make a difference that I am running this from a seperate .js file? I am amending my post to show the full code Commented Oct 17, 2018 at 8:04
  • 1
    Yes it does, the input field does not exist at the point when your JS code is executed. Move the script to the end of body, or execute your code on page load. (Research the latter, if it doesn’t mean anything to you.) Commented Oct 17, 2018 at 8:15
  • Thanks made it work perfectly! :) Commented Oct 17, 2018 at 8:22

2 Answers 2

2

Textareas are not text inputs. Whereas input elements store the input in an attribute: <input value="foo">, textareas get them as content: <textarea>foo</textarea>. Use this instead:

textarea.textContent = "testing123"
Sign up to request clarification or add additional context in comments.

Comments

1

You should use the value property of the <textarea>

This will be consistent around <input> and <select> elements

I would prefer this approach over the textContent approach. It will continue to work, if you would change the textarea to a input.

var textarea = document.getElementById("your_textarea");

textarea.value = "this text is added with JS"
h1 {
  text-align: center;
  font-family: sans-serif;
}
<h1>RELATION TAGGING</h1>
<textarea id="your_textarea" rows="15" cols="160"></textarea>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.