avatar

How to get the value of textarea with javascript DOM?

How to get the value of textarea with javascript DOM?

bounty icon
$10
Single winner
Asked  9 months ago
Viewed  0 times
<textarea name="" id="text" name="text" ></textarea>
<button value="123">发布</button>
<ul>

</ul>
<script>
var button=document.querySelector("button");
var text=document.getElementById("text");
var ul=document.querySelector("ul");
button.onclick=function(){
var li=document.createElement("li");
ul.insertBefore(li,ul.children[0]);
li.innerHTML=text.value;
}

If I change

var text=document.getElementById("text");

to

var text=document.getElementById("text").value;

then

li.innerHTML=text

will not get a value, but I can get the value If i remove the text and use

li.innerHTML=document.getElementById("text").value; 

why?

  • add comment
avatar

var text=document.getElementById("text").value; is executed when the page loads. At this time, the value of the variable is only the initial string of the text box, not the value entered by the user later.

Only by getting the value of value in the button click event function can you get the latest content of the text box.

  • Taken
  • add comment
  • 0
Sign In
Sign In
avatar

How to get the value of textarea with javascript DOM?

How to get the value of textarea with javascript DOM?

bounty icon
$10
Single winner
Asked  9 months ago
Viewed  0 times
<textarea name="" id="text" name="text" ></textarea>
<button value="123">发布</button>
<ul>

</ul>
<script>
var button=document.querySelector("button");
var text=document.getElementById("text");
var ul=document.querySelector("ul");
button.onclick=function(){
var li=document.createElement("li");
ul.insertBefore(li,ul.children[0]);
li.innerHTML=text.value;
}

If I change

var text=document.getElementById("text");

to

var text=document.getElementById("text").value;

then

li.innerHTML=text

will not get a value, but I can get the value If i remove the text and use

li.innerHTML=document.getElementById("text").value; 

why?

  • add comment
avatar

var text=document.getElementById("text").value; is executed when the page loads. At this time, the value of the variable is only the initial string of the text box, not the value entered by the user later.

Only by getting the value of value in the button click event function can you get the latest content of the text box.

  • Taken
  • add comment
  • 0