英文:
Need to save data from an HTML file but bowser gives an undefined error
问题
我的项目有一个注册表单,用于收集用户数据。我连接了JavaScript并尝试让当用户点击注册按钮时,JavaScript文件将其保存为名为input的变量。这是我的HTML代码:
<input type="text" class="loginInfo" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" class="loginInfo" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" class="loginInfo" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn" onclick="othername();">Sign Up</button>
这是我的JavaScript:
function othername() {
var input = document.getElementsByClassName("loginInfo").value;
alert(input);
}
我尝试让变量在HTML中定义,但没有成功。问题是每当用户点击注册按钮时,浏览器都会显示未定义的消息。
英文:
My project has a sign up form that collects user's data. I connected the JavaScript and tried to make it so that when the user hits the sign up button, the JavaScript file saves it as a variable named input. Here is my code for HTML:
<input type="text" class="loginInfo" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" class="loginInfo" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" class="loginInfo" placeholder="Repeat Password" name="psw-repeat" required>
<div class="clearfix">
<button type="submit" class="signupbtn" onclick="othername();">Sign Up</button>
And here is my JavaScript:
function othername() {
var input = document.getElementsByClassName("loginInfo").value;
alert(input);
}
I tried to make it so that the variable was defined in the HTML but it didn't work. The problem is that whenever the user hits the sign up button, the browser gives an undefined message.
答案1
得分: -1
"getElementsByClassName" 返回一个元素数组,而不是单个元素。
如果您想要第一个 "loginInfo" 实例,请使用:
document.getElementsByClassName("loginInfo")[0].value;
或者
document.querySelector(".loginInfo").value;
英文:
As the name suggests, getElementsByClassName
returns an array of elements, not a single element.
If you want the first loginInfo
instance, use:
document.getElementsByClassName("loginInfo")[0].value;
or
document.querySelector(".loginInfo").value;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论