我需要使用JavaScript获取输入值,但我只获得undefined
。这是我的代码:
document.forms[0].elements[0] or
document.forms['form_id']['fieldname']
我的错误在哪里?
这是我的表格:
<form action="registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg-form">
<div>
<label for="username">Username</label>
<input type="text" name="username" required="">
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" required="">
</div>
<div>
<label for="email">E-mail</label>
<input type="text" name="email">
</div>
<div>
<label for="telephone">Telephone</label>
<input type="text" name="telephone">
</div>
<div>
<label for="sex">Sex</label>
<input type="radio" value="male" name="sex">Male
<input type="radio" value="female" name="sex">Female
</div>
<div>
<label for="user_photo">User photo</label>
<input type="file" name="user_photo">
</div>
<div>
<label for="birthDate">Birth Date</label>
<input type="date" name="birthDate">
</div>
<div>
<label for="country">Country</label>
<input type="text" name="country">
</div>
<div>
<label for="info">Info about user</label>
<textarea name="info"></textarea>
</div>
<div>
<input type="hidden" name="PHPSESSID" value="<?php echo session_id(); ?>">
</div>
<div><input type="submit" value="Register"></div>
</form>
表单位于php文件中,可能有问题吗?因为当我登录日志forms.length
时,我得到零......
答案 0 :(得分:1)
您需要将这些DOM对象访问代码放入window.onload事件处理程序中,因为它需要在访问DOM对象之前等待加载的文档。
答案 1 :(得分:0)
你可以尝试例如:
document.forms['reg-form']['email'].value
我认为您可能不会使用
定位正确的Dom元素document.forms['form_id']['fieldname']
请看这个jsfiddle-Sample:
http://jsfiddle.net/3gevoyn5/8/
我有两个输入字段并使用此代码获取值,然后再次输出:
function getValues(){
var test = document.forms['myform']['firstname'].value + " " + document.forms['myform']['lastname'].value;
document.getElementById("demo").innerHTML = test;
}