[SalesForce] Reset the current form without reloading page

In our scenario, we have a form of several apex:inputfield elements and some other input fields. So they have a default value coming from database. We have implemented a cancel button which currently just reload the page to refresh the content. However, I do have a feeling this is low efficiency. I am trying to think about a way do reset the table without reloading the page.

One approach I can think of is to use an apex:actionfunction which can be called when pressing the button and loading the default values again from database then rerender the form. This approach will probably work (I haven't tried) but will still result in large view state. Is there a better (would prefer client side) way of doing this? No is an absolutely acceptable answer.

Best Answer

prerequisite: jQuery; assumption: that you want this to be all client-side and capturing the values as they were initially rendered.

This can be done pretty simply in JavaScript, using jQuery here for ease of implementation.

// array to hold our form's default values as they were rendered
var inputsArray = [];

// iterate the input types in the page and store the value of each of them in the array
function storeValues() {

    jQuery('input:text, textarea, input:checkbox').each(function() {



        var $formElement = jQuery(this),
            key = $formElement.attr('name'),
            value = $formElement.val();

        // capture the values in an array as a key/value pair, but make sure we have a key
        if (key) {
            inputsArray.push([key, value]);
        }

    });

    return false;
}

// iterate the array and set the value on each form element with the value from the array
function resetValues() {

    jQuery(inputsArray).each(function() {

        var $arrayElement = $(this),
            key = $arrayElement[0],
            value = $arrayElement[1];

        // set the value on the HTML form element, make sure we've got a key
        if (key) {
            jQuery("[name='" + key + "']").val(value);
        }
    });

    return false;
}

// example usage
// on document.ready call "storeValues();"
// on cancel / reset button click call "return resetValues();"
Related Topic