Action of not getting invoked when “disabled=t

2019-09-06 10:45发布

问题:

I want the Submit button to be enabled when the T&C checkbox is checked. Though my written logic is working alright the action of h:commandButton is not getting invoked even after it is enabled after checking the checkbox. Initially the button is disabled. The code works fine if I remove the disabled="TRUE" attribute but it doesn't serve the purpose. Here is my code :

<script type="text/javascript">
$(document).ready(start);
function start() {

    $('.testing').click(
            function() {
                if ($(document.getElementById('form2:check'))
                        .is(':checked')) {
                    $(document.getElementById('form2:saveForm'))
                            .removeAttr('disabled');
                } else {
                    $(document.getElementById('form2:saveForm')).attr(
                            'disabled', 'disabled');
                }
            });
                 }
</script>

JSP Code:

<h:form id="form2">
    <div class="testing">
        <h:selectBooleanCheckbox id="check" />
                Agree           
            <li class="buttons ">
                <div class="center">
                    <h:commandButton id="saveForm" styleClass="btTxt submit"
                        type="submit" value="Submit"
                        action="#{declarationFormBean.formSubmit}" disabled="true"></h:commandButton>
                </div>
            </li>
</h:form>

Please help.

回答1:

That's because you're solely removing the disabled attribute in the JSF-generated HTML representation using JavaScript/jQuery. This doesn't change anything to the disabled attribute in the actual JSF component which is consulted during decoding the action event.

This is actually a Good ThingTM of JSF, because otherwise any hacker would be able to bypass any JSF disabled, readonly and rendered attribute by just manipulating the HTML DOM tree while they are initially used to block them like so rendered="#{request.isUserInRole('ADMIN')}".

You need to enable the button by JSF instead of JS/jQuery.

<h:selectBooleanCheckbox binding="#{check}">
    <f:ajax render="saveForm" />
</h:selectBooleanCheckbox>
<h:commandButton id="saveForm" ... disabled="#{not check.value}" />

That's all. No custom JS/jQuery mess necessary, nor any additional JSF bean properties. The above code is complete as-is.

See also:

  • What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?