我需要创建一个重置按钮,在表单重置后将焦点设置在第一个表单字段上

时间:2016-05-23 04:54:30

标签: javascript html5

这是HTML5代码:

<form name="memberInfo">
<table border=1>
<tr><td>Username</td><td><input id="username"   /></td></tr>
<button type = "reset" id = "resetButton">Reset</button>
<input type=button value="submit" onclick="Validate()"/>
</table>
</form>

这是JavaScript代码:

window.onload =function(){
var _getForm = document.getElementById("memberInfo");
_getForm.addEventListener('reset',function(){
document.getElementById("username").focus()
})
}

2 个答案:

答案 0 :(得分:0)

<form id = "myForm">
<input type = "text" id ="text1">
<input type = "text" id ="text2">
<input type = "text" id ="text3">
<button type = "reset" id = "restButton">Reset</button>
</form> 

JS

$("#myForm").submit(function()
{
$('#myForm').trigger("reset");
$('#text1').focus();
return true;
});

答案 1 :(得分:-1)

使用button type ="reset"focus()

希望此代码段有用

HTML

<form id = "myForm">
    <input type = "text" id ="text1">
    <input type = "text" id ="text2">
    <input type = "text" id ="text3">
    <button type = "reset" id = "restButton">Reset</button>
    </form>

JS

   var _getForm = document.getElementById("myForm");
    _getForm.addEventListener('reset',function(){
    document.getElementById("text1").focus()
    })

选中此jsfiddle

修改

您可以使用firstElementChild代替document.getElementById("firtChild")

更新了jsFiddle

修改-2

如果您已将代码放在head标记内,则可以在窗口加载后使用window.onload附加eventlistener

 window.onload =function(){
    var _getForm = document.getElementById("your form id");
    _getForm.addEventListener('reset',function(){
    document.getElementById("text1").focus()
    })
    }

修改-3

对于原始问题的最新更改,这里有一些更新

请注意

  1. id=memberInfovar没有表格。有name="memberInfovar"的表单。因此_getForm = document.getElementById("memberInfo");会抛出addEventListener of null
  2. <input id="username" />添加此输入的类型,即input type = "text"
  3. <input type=buttontype必须包含在双引号内,即<input type="button">
  4. 选中此jsfiddle