[英]How to get input provided in a textarea tag using JavaScript?
Have a textarea
tag in form, to take input text and return the value of said text. 具有textarea
标记形式,以获取输入文本并返回所述文本的值。
<textarea id="code" name="code"></textarea>
Using javascript to get the value, but it returns nothing. 使用javascript获取值,但不返回任何内容。 Used typeof
to check if it's undefined
, but typeof text
gives 'string'
. 使用typeof
来检查它是否undefined
,但是typeof text
给出'string'
。 Is this correct way to use .value
? 这是使用.value
正确方法吗? How to improve this? 如何改善呢?
JavaScript: JavaScript的:
var text = document.getElementById('code').value;
document.getElementById('submit-button').onclick = function() {
alert(text);
};
You're getting the value immediately when the page loads, before the user has had a chance to type anything. 当用户有机会键入任何内容时,您将在页面加载后立即获得该值。 You want to get the value when the user clicks the button: 您想在用户单击按钮时获取值:
document.getElementById('submit-button').onclick = function() { var text = document.getElementById('code').value; alert(text); };
<textarea id="code" name="code"></textarea> <button type="button" id="submit-button">click me</button>
You need to bind the event and get the value just when the user clicks the button. 您需要绑定事件并仅在用户单击按钮时获取值。
Embrace the function addEventListener
拥抱功能addEventListener
document.getElementById('submit-button').addEventListener('click', function() { var text = document.getElementById('code').value; console.log(text); });
<textarea id="code" name="code"></textarea> <button type="button" id="submit-button">click me</button>
Stick the var text
line inside the click event; 将var text
行粘贴在click事件中; it's getting defined when the script runs originally, so it is just an empty string. 它是在脚本最初运行时定义的,因此它只是一个空字符串。
document.getElementById('submit-button').onclick = function() {
var text = document.getElementById('code').value;
alert(text);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.