Getting the values of textboxes in Javascript(在 Javascript 中获取文本框的值)
问题描述
我有这个 html 代码:
I have this html code:
<table border="" cellpadding="3" cellspacing="0" id="mytable">
<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
如何获得歌曲"和艺术家"的值?我试过了:
How do I get the values of "song" and "artist"? I have tried:
var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
但即使文本框中有文本,我也会不断收到未定义"
but I keep getting "undefined" even when there is text inside the textbox
推荐答案
首先,td元素没有value属性,所以调用.value 他们不会做任何事情.其次,该值实际上在 input 元素上,因此您需要改为 mytable.getElementsByTagName('input') .更好的是给你的输入字段ID,然后使用getElementById.这意味着您可以在不破坏 JS 的情况下更改 HTML.
First, td elements don't have a value attribute, so calling .value on them won't do a thing. Second, the value is actually on the input element, so you need to do mytable.getElementsByTagName('input') instead. Even better would be to give your input fields ids and then use getElementById. This would mean you could alter your HTML without your JS breaking.
这篇关于在 Javascript 中获取文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Javascript 中获取文本框的值
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
