将表单字段重置为初始状态

Reseting form fields to initial state

本文关键字:初始状态 表单 字段      更新时间:2023-09-26

我使用下面的代码使用Jquery设置我的表单字段

 $("#frmlogin").reset()
上面的

是我用来重置下面表单

中的字段的代码
<form  name='frmlogin' method='POST' id="login_form" style="margin:0 auto; margin-top:50px; width: 40%; height:300px; text-align:center;">
                        <input class="oFormJumbo oFormMed oInputText" type="text" name="requiredLogin" placeholder="Login Id" AUTOCOMPLETE=OFF />
                        <div class="cleaner h10"></div>
                        <input class="oFormJumbo oFormMed oInputText "  type="password" value="" name="password" placeholder="Password"  AUTOCOMPLETE=OFF onfocus="changetoUpperCase(document.frmlogin.requiredLogin.value);" />
                        <div class="cleaner h10"></div>
                        <a href="javascript:fp();">Forgot Password?</a>
                        <div class="cleaner"></div>
                        <input style="margin-left:0px; "   class="submit_btn float_l" type="button" value="Sign In" name="Sign In" onClick="javascript:func_get_data();"/>
                        <input style="margin-left: 200px; "  class="submit_btn float_r" type="button" value="Reset" id="reset" name="reset"   onclick="javascript:Reset()"/>
 </form>

由于某些原因,代码不能工作。JavaScript抛出以下异常

TypeError: $("#frmlogin").reset is not a function
[Break On This Error]   
$("#login_form").reset()

谁能告诉我为什么它不工作?我已经包含了Jquery.js。

根据Adils的建议,我甚至尝试了

*$("#login_form")[0].reset()*

现在是

TypeError: $("#frmlogin")[0] is undefined
[Break On This Error]   
$("#frmlogin")[0].reset()

我错过了什么?

我尝试了下面建议的所有代码,除了Amit Agrawal,因为我想使用Jquery。没有锅。我知道我的代码休息是提供的。在

这个表单中我缺少了一些东西

是否有什么原因导致您忽略了reset input元素?

http://jsfiddle.net/BhTv5/

<input type="reset" />

你正在使用jQuery对象来调用reset,使用DOM对象来调用reset,你可以使用indexer将jQuery对象转换为DOM对象。

改变
$("#login_form").reset()

$("#login_form")[0].reset()

编辑基于评论,问题的另一个原因是id和您的重置按钮的名称。令人惊讶的是,如果有任何带有id或名称reset的输入,那么form.reset()函数将停止工作。修改复位按钮的id和名称,上面的代码就可以工作了

现场演示

改变
<input style="margin-left: 200px; "  class="submit_btn float_r" type="button" value="Reset" id="reset" name="reset"   onclick="javascript:Reset()/>

<input style="margin-left: 200px; "  class="submit_btn float_r" type="button" value="Reset" id="myreset" name="myreset" />

用按钮绑定事件

$('#myreset').click(function () {   
    $("#login_form")[0].reset();
});

试试这段代码,你不会得到类型错误。您声明的表单名称不是id,请尝试使用id并重置表单。

document.getElementById("login_form").reset();

(或)

  $("#login_form").reset();

重置为javascript方法,需要DOM对象

应该是

$("#login_form")[0].reset()

您必须获得具有属性选择器的name:

$('form[name="frmlogin"]').reset();

或id:

$('#login_form').reset();

您的代码中断,因为您没有使用正确的属性引用表单

使用JavaScript

document.getElementById("login_form").reset();//Use the id of the form
使用jQuery

("#login_form").reset();