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 中获取文本框的值
基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01