Resetting a multi-stage form with jQuery

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

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


Trouble i

相关标签:
30条回答
  • 2020-11-22 01:28

    jQuery Plugin

    I created a jQuery plugin so I can use it easily anywhere I need it:

    jQuery.fn.clear = function()
    {
        var $form = $(this);
    
        $form.find('input:text, input:password, input:file, textarea').val('');
        $form.find('select option:selected').removeAttr('selected');
        $form.find('input:checkbox, input:radio').removeAttr('checked');
    
        return this;
    }; 
    

    So now I can use it by calling:

    $('#my-form').clear();
    
    0 讨论(0)
  • 2020-11-22 01:28

    Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:

    function resetForm(formId){
            $('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
            $('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
            $('.select2').select2();
        }
    
    0 讨论(0)
  • 2020-11-22 01:30

    I'm just an intermediate in PHP, and a bit lazy to dive into a new language like JQuery, but isn't the following a simple and elegant solution?

    <input name="Submit1" type="submit" value="Get free quote" />
    <input name="submitreset" type="submit" value="Reset" />
    

    Can't see a reason why not have two submit buttons, just with different purposes. Then simply:

    if ($_POST['submitreset']=="Reset") {
    $_source = "--Choose language from--";
    $_target = "--Choose language to--"; }
    

    You just redefine your values back to whatever the default is supposed to be.

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

    Here is something to get you started

    $('form') // match your correct form 
    .find('input[type!=submit], input[type!=reset]') // don't reset submit or reset
    .val(''); // set their value to blank
    

    Of course, if you have checkboxes/radio buttons, you'll need to modify this to include them as well and set .attr({'checked': false});

    edit Paolo's answer is more concise. My answer is more wordy because I did not know about the :input selector, nor did I think about simply removing the checked attribute.

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

    I find this works well.

    $(":input").not(":button, :submit, :reset, :hidden").each( function() {
        this.value = this.defaultValue;     
    });
    
    0 讨论(0)
  • 2020-11-22 01:31

    Here with the refresh for checkboxes and selects:

    $('#frm').find('input:text, input:password, input:file, textarea').val('');
    $('#frm').find('input:radio, input:checkbox').attr("checked",false).checkboxradio("refresh");
    $('#frm').find('select').val('').selectmenu('refresh');
    
    0 讨论(0)
提交回复
热议问题