Javascript Get Element by Id and set the value
Given
<div id="This-is-the-real-id"></div>
then
function setText(id,newvalue) {
var s= document.getElementById(id);
s.innerHTML = newvalue;
}
window.onload=function() { // or window.addEventListener("load",function() {
setText("This-is-the-real-id","Hello there");
}
will do what you want
Given
<input id="This-is-the-real-id" type="text" value="">
then
function setValue(id,newvalue) {
var s= document.getElementById(id);
s.value = newvalue;
}
window.onload=function() {
setValue("This-is-the-real-id","Hello there");
}
will do what you want
function setContent(id, newvalue) {
var s = document.getElementById(id);
if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;
else s.innerHTML = newvalue;
}
window.addEventListener("load", function() {
setContent("This-is-the-real-id-div", "Hello there");
setContent("This-is-the-real-id-input", "Hello there");
})
<div id="This-is-the-real-id-div"></div>
<input id="This-is-the-real-id-input" type="text" value="">
Coming across this question,
no answer brought up the possibility of using .setAttribute()
in addition to .value()
document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");
Though unlikely helpful for the original questioner,
this addendum actually changes the content of the value in the pages source,
which in turn makes the value update form.reset()
-proof.
I hope this may help others.
(Or me in half a year when I've forgotten about js quirks...)
<html>
<head>
<script>
function updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>
<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"
onKeyUp="updateTextarea('myDiv')" />
<br>
<textarea id="myDiv" ></textarea>
</body>
</html>
If myFunc(variable) is executed before textarea is rendered to page, you will get the null exception error.
<html>
<head>
<title>index</title>
<script type="text/javascript">
function myFunc(variable){
var s = document.getElementById(variable);
s.value = "new value";
}
myFunc("id1");
</script>
</head>
<body>
<textarea id="id1"></textarea>
</body>
</html>
//Error message: Cannot set property 'value' of null
So, make sure your textarea does exist in the page, and then call myFunc, you can use window.onload or $(document).ready function. Hope it's helpful.