[英]How to read text from HTML input in JavaScript function?
On the webpage, the user is able to write text in a text field. 在网页上,用户可以在文本字段中编写文本。 I would like to use the button on this page to read this text and then place it somewhere else.
我想使用此页面上的按钮阅读此文本,然后将其放置在其他位置。 Here is the simplified markup so far:
到目前为止,这是简化的标记:
<div id="Demo1" class="w3-accordion-content w3-container">
<h4>Let's make your Resume Header</h4>
<table>
<tr>
<th>Name</th>
<td><input type="text" id="name"></td>
</tr>
</table>
<button onclick="header()" class="save">SAVE</button>
</div>
And here is the JavaScript code that I have: 这是我拥有的JavaScript代码:
function header() {
var name = document.getElementById(name).value;
alert(name);
}
This alert does not work at all when I run it. 运行此警报时,它根本不起作用。 I cannot figure out why, any help is much appreciated.
我不知道为什么,非常感谢您的帮助。
You must wrap the elementById argument in quotes, as well as have a way for your HTML to reference your JavaScript. 您必须将elementById参数用引号引起来,并且必须为HTML引用JavaScript提供一种方法。 See Below.
见下文。
<script>
function header() {
var name = document.getElementById("name").value;
alert(name);
}
</script>
<div id="Demo1" class="w3-accordion-content w3-container">
<h4>Let's make your Resume Header</h4>
<table>
<tr>
<th>Name</th>
<td><input type="text" id="name"></td>
</tr>
</table>
<button onclick="header()" class="save">SAVE</button>
</div>
You have missed quotes. 您错过了报价。 So use
document.getElementById('name').value
instead of document.getElementById(name).value
. 因此,请使用
document.getElementById('name').value
代替document.getElementById(name).value
。
if you use name
as a parameter then you can use it without quotes. 如果使用
name
作为参数,则可以使用不带引号的名称。
function header() { var name = document.getElementById('name').value; alert(name); }
<div id="Demo1" class="w3-accordion-content w3-container"> <h4>Let's make your Resume Header</h4> <table> <tr> <th>Name</th> <td> <input type="text" id="name"> </td> </tr> </table> <button onclick="header()" class="save">SAVE</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.