Search code examples
jsfjsf-2

Avoid form submission if no input value changed


Is there any way in JSF2 we can avoid the form submission, or simply do not do anything when form is submitted?

We have several input fields (20 input fields) in a form, which are filled with some default values, if no value is changed then we don't want to submit the form.

Is there any direct way in JSF we can achieve this?

<h:form id="summaryForm" prependId="false">
     <h:inputText id="inputField1" value="#{summaryBean.inputFieldValue1}" />
     <h:inputText id="inputField2" value="#{summaryBean.inputFieldValue2}" />
     <h:inputText id="inputField3" value="#{summaryBean.inputFieldValue3}" />
     <h:inputText id="inputField4" value="#{summaryBean.inputFieldValue4}" />
     <h:inputText id="inputField5" value="#{summaryBean.inputFieldValue5}" />
     <h:commandButton action="#{summaryBean.submitSummary}" />
</h:form>

Solution

  • The short answer is no, in plain JSF you can't do that. You can do it on the client side with a bit of JavaScript and jQuery, though.

    ... include jQuery somewhere here ...
    
    <script>
    var anyInputChanged = false;
    var checkIfAnyValueChanged = function(){ return anyInputChanged; };
    (function($) {
        $(function() {
            // set variable anyInputChanged to TRUE on event 'onchange',
            //    for the fields with class "submitOnlyIfChanged"
            $('.submitOnlyChanged').change(function(){ anyInputChanged = true; });
        });
    })(jQuery);
    </script>
    
    <h:form id="summaryForm" prependId="false">
        <!-- set up all the fields with the class "submitOnlyIfChanged" -->
        <h:inputText class="submitOnlyIfChanged" id="inputField1"
           value="#{summaryBean.inputFieldValue1}" />
        <h:inputText class="submitOnlyIfChanged" id="inputField2"
           value="#{summaryBean.inputFieldValue2}" />
        <h:inputText class="submitOnlyIfChanged" id="inputField3"
           value="#{summaryBean.inputFieldValue3}" />
    
        <!-- set up a check if any field was changed on button click -->
        <h:commandButton onclick="return checkIfAnyValueChanged();"
           action="#{summaryBean.submitSummary}" />
    </h:form>