Clear form fields with jQuery

前端 未结 30 3300
甜味超标
甜味超标 2020-11-22 15:48

I want to clear all input and textarea fields in a form. It works like the following when using an input button with the reset class:

$(\".reset         


        
30条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 16:19

    I've written a universal jQuery plugin:

    /**
     * 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();
            }
        });
    });
    
    

    Form



    Ch 1 (default checked)
    Ch 2
    Ch 3 (default checked)



    R 1
    R 2 (default checked)
    R 3



    Play with form values and then try to reset them

提交回复
热议问题