【问题标题】:JavaScript only returns undefined in html [duplicate]JavaScript仅在html中返回未定义[重复]
【发布时间】:2021-06-08 07:10:15
【问题描述】:
这是我的代码:
function INVIO() {
var nome = document.getElementsByName("userName").value;
var password = document.getElementsByName("userPassword").value;
var email = document.getElementsByName("userMail").value;
var messaggio = nome + ", abbiamo registrato la tua password (" + password + ") e la tua mail (" + email + ")";
document.getElementById("risultato").innerHTML = messaggio;
}
<b>Username:</b>
<input id="userName" type="text" name="userName" /><br><br>
<b>Password:</b>
<input id="userPassword" type="password" name="userPassword" /><br><br>
<b>Email:</b>
<input id="userMail" type="email" name="userMail" /><br><br>
<button type="button" onclick="INVIO();">
<font color="black">
<b>INVIO</b>
</font>
</button>
<p id="risultato"></p>
This is the problem:所有值都显示为undefined。
我在整个网站上搜索了答案,但没有找到任何答案。
例如,关于如何使用 JavaScript 从 iframe 中获取值的答案充满了答案,但没有人对输入标签有任何问题。
我会感谢任何可以帮助我的人。
【问题讨论】:
标签:
javascript
html
getelementbyid
getelementsbyname
【解决方案1】:
您应该使用 getElementById 而不是 getElementsByName
var nome = document.getElementById("userName").value;
var password = document.getElementById("userPassword").value;
var email = document.getElementById("userMail").value;
document.getElementsByName 返回文档中具有指定名称的所有元素的集合,而不是单个元素
<b>Username:</b>
<input id="userName" type="text" class="input_arancione" title="Il tuo userName" name="userName"/><br><br><br>
<b>Password:</b>
<input id="userPassword" type="password" class="input_arancione" title="Un numero compreso tra 8 e 12 cifre HEX" name="userPassword"/><br><br><br>
<b>Email:</b>
<input id="userMail" type="email" class="input_arancione" title="Il tuo indirizzo mail" name="userMail"/><br><br><br>
<button type="button" class="button" onclick="INVIO();">
<font color="black">
<b>
INVIO
</b>
</font>
</button>
<!--Some useless code between-->
<script type="text/javascript">
function INVIO()
{
var nome = document.getElementById("userName").value;
var password = document.getElementById("userPassword").value;
var email = document.getElementById("userMail").value;
var messaggio = nome + ", abbiamo registrato la tua password (" + password + ") e la tua mail (" + email + ")";
document.getElementById("risultato").innerHTML = messaggio;
}
</script>
<p id="risultato"></p>
【解决方案2】:
使用 document.getElementById 代替 document.getElementsByName。
function INVIO()
{
var nome = document.getElementById("userName").value;
var password = document.getElementById("userPassword").value;
var email = document.getElementById("userMail").value;
var messaggio = nome + ", abbiamo registrato la tua password (" + password + ") e la tua mail (" + email + ")";
document.getElementById("risultato").innerHTML = messaggio;
}