Clear Form on Back Button?

后端 未结 4 905
太阳男子
太阳男子 2020-12-16 04:46

I have a page with several check-boxes in a form, which when selected, filter corresponding info out of a table with jquery. My problem is the following scenario:

相关标签:
4条回答
  • 2020-12-16 05:15

    If your objective is to bring them back to the exact view they had before they left (table rows are still hidden):

    Such is a disadvantage (or advantage) of a website: it's stateless, particularly when it comes to client-side manipulation.

    What you'll need to do is store the application state in the URL hash tag so that when the user uses their back button, you can retrieve the "state" and reconstruct their view.

    Here's another question whose answer might help you: jquery javascript: adding browser history back with hashtag?

    If your objective is to return the page back to its initial state:

    Just reset all the checkboxes on page load:

    $('input:checkbox').prop('checked', false);
    

    -or-

    Reset the entire form:

    $(':input','#myform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .prop('checked', false)
     .prop('selected', false);
    
    0 讨论(0)
  • 2020-12-16 05:19

    So your problem is not with the browser caching the user input but with the rows not being hidden. You can easily solve this problem by adding a jQuery script that will check if a checkbox is checked (after loading the page). If it's checked, you hide the row :)

    pseudocode:

    1. wait for the page to load
    2. for each checkbox check if checked
    3. if it's checked, hide the corresponding row in the same way you did when the user checked it.
    
    0 讨论(0)
  • 2020-12-16 05:23

    Do not allow your page to be cached, or add code to reset your form:

    $("form input").each(function(){
        var elem = $(this);
        var type = elem.attr("type");
        if(type == "checkbox") elem.prop("checked", "");
        else if(type == "text") elem.val("");
    });
    

    .each has to be used, because the CSS selector input[type=text] doesn't match <input />, while the element is still a text element.

    0 讨论(0)
  • 2020-12-16 05:23

    For IE resetting the form after submit, did not help for me. Instead following code worked for me. Page load event gets called on browser Back Button as well.

    $(window).load(function() {
        $('form').get(0).reset(); //clear form data on page load
    });
    
    0 讨论(0)
提交回复
热议问题