Resetting a multi-stage form with jQuery

前端 未结 30 1988
谎友^
谎友^ 2020-11-22 00:58

I have a form with a standard reset button coded thusly:


Trouble i

相关标签:
30条回答
  • 2020-11-22 01:20
    $(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);
    
    0 讨论(0)
  • 2020-11-22 01:22

    this worked for me , pyrotex answer didn' reset select fields, took his, here' my edit:

    // Use a whitelist of fields to minimize unintended side effects.
    $(':text, :password, :file', '#myFormId').val('');  
    // De-select any checkboxes, radios and drop-down menus
    $(':input,select option', '#myFormId').removeAttr('checked').removeAttr('selected');
    //this is for selecting the first entry of the select
    $('select option:first', '#myFormId').attr('selected',true);
    
    0 讨论(0)
  • 2020-11-22 01:22

    I made a little improvement on Paolo Bergantino's original answer

    function resetFormInputs(context) {
        jQuery(':input', context)
        .removeAttr('checked')
        .removeAttr('selected')
        .not(':button, :submit, :reset, :hidden')
        .each(function(){
             jQuery(this).val(jQuery(this).prop('defautValue'));
        });
    }
    

    In this way, I can pass any context element to the function. I am able to reset the entire form or only a certain set of fields, for example:

    resetFormInputs('#form-id'); // entire form
    resetFormInputs('.personal-info'); // only the personal info field set
    

    Plus, the default values of the inputs are retained.

    0 讨论(0)
  • 2020-11-22 01:22

    here is my solution, which also works with the new html5 input-types:

    /**
     * removes all value attributes from input/textarea/select-fields the element with the given css-selector
     * @param {string} ele css-selector of the element | #form_5
     */
    function clear_form_elements(ele) {
        $(ele).find(':input').each(function() {
            switch (this.type) {
                case 'checkbox':
                case 'radio':
                    this.checked = false;
                default:
                    $(this).val('');
                    break;
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-22 01:23

    I normally add a hidden reset button to the form. when needed just: $('#reset').click();

    0 讨论(0)
  • 2020-11-22 01:24
    <script type="text/javascript">
    $("#edit_name").val('default value');
    $("#edit_url").val('default value');
    $("#edit_priority").val('default value');
    $("#edit_description").val('default value');
    $("#edit_icon_url option:selected").removeAttr("selected");
    </script>
    
    0 讨论(0)
提交回复
热议问题