首页 文章

使用jQuery清除表单字段

提问于
浏览
344

我想清除表单中的所有输入和textarea字段 . 当使用 reset 类的输入按钮时,它的工作方式如下:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

这将清除页面上的所有字段,而不仅仅是表单中的字段 . 我的选择器如何仅仅是实际重置按钮所在的形式?

27 回答

  • 2
    $('#editPOIForm').each(function(){ 
        this.reset();
    });
    

    其中 editPOIForm 是表单的 id 属性 .

  • 0

    我用这个:

    $(".reset").click(function() {
      $('input[type=text]').each(function(){
         $(this).val('');
      });
    });
    

    这是我的按钮:

    <a href="#" class="reset">
      <i class="fa fa-close"></i>
         Reset
    </a>
    
  • 27
    $(".reset").click(function() {
        $(this).closest('form').find("input[type=text], textarea").val("");
    });
    
  • 1

    简单,但工作就像一个魅力 .

    $("#form").trigger('reset'); //jquery
    document.getElementById("myform").reset(); //native JS
    
  • 11

    $('form') . submit(function(){

    var el = $(this);
    
    $('<button type="reset" style="display:none; "></button>')
        .appendTo(el)
        .click()
        .remove()
    ;
    
    return false;
    

    });

  • 45

    以下代码清除所有表单,它的字段将为空 . 如果您希望仅在页面包含多个表单时清除特定表单,请提及表单的ID或类别

    $("body").find('form').find('input,  textarea').val('');
    
  • 0

    For jQuery 1.6+

    $(':input','#myform')
      .not(':button, :submit, :reset, :hidden')
      .val('')
      .prop('checked', false)
      .prop('selected', false);
    

    For jQuery < 1.6

    $(':input','#myform')
      .not(':button, :submit, :reset, :hidden')
      .val('')
      .removeAttr('checked')
      .removeAttr('selected');
    

    请看这篇文章:Resetting a multi-stage form with jQuery

    要么

    $('#myform')[0].reset();
    

    作为jQuery suggests

    要检索和更改DOM属性(如表单元素的已选中,已选择或已禁用状态),请使用.prop()方法 .

  • 11

    让我们说如果你想清除字段和accountType,平均时间下拉框将被重置为特定值,即'All'.Remaining字段应该重置为空即文本框 . 这种方法将用于清除特殊领域作为我们的要求 .

    $(':input').not('#accountType').each( function() {
    
        if(this.type=='text' || this.type=='textarea'){
                 this.value = '';
           }
        else if(this.type=='radio' || this.type=='checkbox'){
             this.checked=false;
          }
             else if(this.type=='select-one' || this.type=='select-multiple'){
                  this.value ='All';
         }
     });
    
  • -3

    添加隐藏的重置按钮如下

    <input id="resetBtn" type="reset" value="reset" style="display:none" />
    // Call reset buttons click event
    // Similar to ClearInputs('resetBtn');
    function ClearInputs(btnSelector) {
         var btn = $("#" + btnSelector);
         btn.click();
    }
    
  • 425
    @using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
    {
        OnSuccess = "ClearInput",
        HttpMethod = "Post",
        UpdateTargetId = "defect-list",
        InsertionMode = InsertionMode.Replace
    }, new { @id = "frmID" }))
    
    • frmID 是表格的标识

    • OnSuccess 我们称之为JavaScript函数的操作名为“ ClearInput

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
    • 如果你同时做到这两件事,你将无法阻止它工作......
  • 0

    如果你想清空所有输入盒而不管它的类型,那么它只需要一分钟

    $('#MyFormId')[0].reset();
    
  • 3

    我写了一个通用的jQuery插件:

    /**
     * Resets any input field or form
     */
    $.fn.uReset = function () {
        return this.filter('form, :input').each(function () {
            var input = $(this);
            
            // Reset the form.
            if (input.is('form')) {
                input[0].reset();
                return;
            }
    
            // Reset any form field.
            if (input.is(':radio, :checkbox')) {
                input.prop('checked', this.defaultChecked);
            } else if (input.is('select')) {
                input.find('option').each(function () {
                    $(this).prop('selected', this.defaultSelected);
                });
            } else if (this.defaultValue) {
                input.val(this.defaultValue);
            } else {
                console.log('Cannot reset to default value');
            }
        });
    };
    
    $(function () {
        // Test jQuery plugin.
        $('button').click(function (e) {
            e.preventDefault();
            
            var button = $(this),
                inputType = button.val(),
                form = button.closest('form');
            
            if (inputType === 'form') {
                form.uReset()
            } else {
                $('input[type=' + inputType + '], ' + inputType, form).uReset();
            }
        });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h3>Form</h3>
    <form>
        <input type="text" value="default"/>

    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" />
    Ch 2 <input type="checkbox" name="color" value="2" />
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" />

    <select name="time">
    <option value="15">15</option> <option selected="selected" value="30">30</option> <option value="45">45</option> </select>

    R 1 <input type="radio" name="color" value="1" />
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" />
    R 3 <input type="radio" name="color" value="3" />

    <textarea>Default text</textarea>

    <p>Play with form values and then try to reset them</p> <button type="button" value="text">Reset text input</button> <button type="button" value="checkbox">Reset checkboxes</button> <button type="button" value="select">Reset select</button> <button type="button" value="radio">Reset radios</button> <button type="button" value="textarea">Reset textarea</button> <button type="button" value="form">Reset the Form</button> </form>
  • 0

    经过测试和验证的代码:

    $( document ).ready(function() {
        $('#messageForm').submit(function(e){
           e.preventDefault();
        });
        $('#send').click(function(e){
          $("#messageForm")[0].reset();
        });
      });
    

    Javascript必须包含在 $(document).ready 中,并且必须与您的逻辑一致 .

  • 20

    如果你使用选择器并使值为空值,它不会重置表单,它会使所有字段为空 . 重置是在从服务器端加载表单之后,从用户进行任何编辑操作之前的格式 . 如果存在名称为“username”的输入并且该用户名是从服务器端预填充的,则此页面上的大多数解决方案将从输入中删除该值,而不是将其重置为用户更改之前的值 . 如果您需要重置表单,请使用以下命令:

    $('#myform')[0].reset();
    

    如果您不需要重置表单,但用一些值填充所有输入,例如空值,那么您可以使用其他注释中的大多数解决方案 .

  • 5

    有什么理由不应该使用?

    $("#form").trigger('reset');
    
  • 10
    $('form[name="myform"]')[0].reset();
    
  • 1

    使用此代码您想通过jQuery调用Normal Reset Function

    setTimeout("reset_form()",2000);
    

    并在Document Ready上将此功能写出站点jQuery

    <script>
    function reset_form()
    {
        var fm=document.getElementById('form1');
        fm.reset();
    }
    </script>
    
  • 5

    这不会处理表单输入字段具有非空默认值的情况 .

    有点像应该工作

    $('yourdiv').find('form')[0].reset();
    
  • 2

    我有最简单的技巧来重置表单

    jQuery("#review-form")[0].reset();
    

    要么

    $("#review-form").get().reset();
    
  • -3

    当页面包含对涉及IHttpHandler请求处理(captcha)的Web用户控件的调用时,以上都不适用于简单的情况 . 在发送requsrt(用于图像处理)之后,下面的代码不会清除表单上的字段(在发送HttpHandler请求之前),每个事件都能正常工作 .

    <input type="reset"  value="ClearAllFields" onclick="ClearContact()" />
    
     <script type="text/javascript">
           function ClearContact() {
               ("form :text").val("");
           }
        </script>
    
  • 15

    最简单和最好的解决方案是 -
    $("#form")[0].reset();

    不要在这里使用 -
    $(this)[0].reset();

  • 0

    为什么你不使用 document.getElementById("myId").reset(); ?这很简单漂亮

  • 58

    我在这里看到的代码以及相关的SO问题似乎都不完整 .

    重置表单意味着从HTML中设置原始值,所以我把它放在一起,根据上面的代码我正在做的一个小项目:

    $(':input', this)
                    .not(':button, :submit, :reset, :hidden')
                    .each(function(i,e) {
                        $(e).val($(e).attr('value') || '')
                            .prop('checked',  false)
                            .prop('selected', false)
                    })
    
                $('option[selected]', this).prop('selected', true)
                $('input[checked]',   this).prop('checked',  true)
                $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })
    

    如果我遗漏任何东西或任何可以改进的东西,请告诉我 .

  • 141

    如果有人还在阅读这个帖子,这里是最简单的解决方案,不是使用jQuery,而是使用简单的JavaScript . 如果输入字段在表单内,则有一个简单的JavaScript重置命令:

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

    更多关于它:http://www.w3schools.com/jsref/met_form_reset.asp

    干杯!

  • 28

    使用Javascript,您可以使用此语法执行此操作 getElementById("your-form-id").reset();

    您也可以通过这种方式调用reset函数来使用jquery $('#your-form-id')[0].reset();

    记住不要忘记 [0] . 如果,您将收到以下错误

    TypeError:$(...) . reset不是函数

    JQuery还提供了一个可以使用的事件

    $('#form_id') . trigger(“reset”);

    我试过,它的工作原理 .

    注意:重要的是要注意这些方法只将表单重置为服务器在页面加载时设置的初始值 . 这意味着如果在进行随机更改之前将输入设置为值“设置值”,则在调用reset方法后,该字段将重置为相同的值 .

    希望能帮助到你

  • 568

    为什么需要使用任何JavaScript?

    <form>
        <!-- snip -->
        <input type="reset" value="Reset"/>
    </form>
    

    http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


    先尝试一下,它不会清除具有默认值的字段 .

    这是用jQuery做的一种方法,然后:

    $('.reset').on('click', function() {
        $(this).closest('form').find('input[type=text], textarea').val('');
    });
    
  • 6

    如果我想清除除accountType之外的所有字段 . 使用以下内容

    $q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
    

相关问题