在 Javascript 中获取文本框的值

Getting the values of textboxes in Javascript(在 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 中获取文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
quot;Each child in an array should have a unique key propquot; only on first time render of page(“数组中的每个孩子都应该有一个唯一的 key prop仅在第一次呈现页面时)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)