Javascript doesn't work with jsf commandButton

1.1k views Asked by At

I have this code:

<h:commandButton value="Login as Administrator" id="login"
                        data-loading-text="Loading..." class="btn btn-primary"
                        action="#{adminController.loginAdmin}"/>

                    <script>
                         $('#login').on('click', function() {
                            var $btn = $(this).button('loading')
                            // business logic...
                            $btn.button('reset')
                        })
                    </script>

I don't know why I can't call my javascript function. No change will show when i click the button, it execute only the action. I have take this script from bootstrap javascript, section button. http://getbootstrap.com/javascript/#buttons

Thanks for help.

1

There are 1 answers

0
user1983983 On

As you most likely have a form wrapping the button and the form is a UINamingContainer, the ID of the form will be prepended to the one of the button. So the resulting ID in the HTML will be something like form:login and that is why the eventlistener is not added to the button.

You have to know that what you write in the XHTML will be parsed by JSF and then a generated HTML will be sent to the user. So what you write is not what you get to see in the browser.

Now you could have a look at the generated HTML to get the actual ID of the button and use that one. But as you are using JSF it is much better to use the builtin attributes of the h:commandButton, i.e. onclick and specify a JS function there which does the stuff you want to do on click. And maybe you want to use oncomplete also to reset the label of the button when the action is finished.

<h:commandButton value="Login as Administrator" id="login"
   action="#{adminController.loginAdmin}" onclick="login()"/>

 <script>
   function login() {
     var $btn = $(this).button('loading');
     // business logic...
     $btn.button('reset');
   }
 </script>

You should also be aware that data-loading-text will not find its way through the JSF parser, so you will not see this property on the generated HTML button.