0

I have very specific requirement that uses JavaScript, JSF 2 and Ajax feature of JSF 2. I have a drop-down list with two values. Say A and B.

<h:selectOneMenu class="form-control" id="sampleList" value="#{beanName.tempValue}">
    <f:selectItem itemLabel="Select value..." itemValue="0" />
    <f:selectItem itemLabel="A" itemValue="a" />
    <f:selectItem itemLabel="B" itemValue="b" />
    <f:ajax event="change" listener="#{beanName.actionMethodToNavigate}" onevent="if (this.value=='0'){ return false;} else if (this.value=='a'){jumpToAhchor('#listItems');return false;}"/>
</h:selectOneMenu>

If the drop down value is "a" then user stays on the same page and anchors to other element down on the same screen using JavaScript. If the value is B then it calls bean method, which eventually navigates user to other screen.

I have tried to search many examples, and many suggest to put JavaScript in onevent attribute. But it does not work in my case and getting this console error in browser.

enter image description here

01000001
  • 833
  • 3
  • 8
  • 21
  • You need to more code, for example - your JS code etc. Provided code is too less to find the root cause .. – hagrawal7777 Aug 16 '18 at 12:59
  • Thanks for looking into it. But I found a solution, and realized that i was doing it wrong. "onevent" accepts function name not JavaScript code. – 01000001 Aug 16 '18 at 18:21
  • 1
    It **_IS_** a duplicate since the generic/common/underlying problem is the same. Learning to see this is a major thing in finding solutions to problems quicker – Kukeltje Aug 30 '18 at 21:35
  • "Learning to see this is a major thing in finding solutions to problems quicker" - Agreed! – 01000001 Aug 31 '18 at 15:04

1 Answers1

0

Anyway I found the solution and thought it will help. Some valuable findings:
1. If you want to access bean variables in JavaScript, put the script inside form.
2. function inside "onevent" has its own variable called "data" and has different statuses(begin, complete and success). Do your task only when the status is "success" otherwise it will run 3 times.
3. JSF and Jquery AJAX - How can I make them work together? - Refer to this for more info on statuses

<h:selectOneMenu class="form-control" id="sampleList" value="#{beanName.tempValue}">
    <f:selectItem itemLabel="Select value..." itemValue="0" />
    <f:selectItem itemLabel="A" itemValue="a" />
    <f:selectItem itemLabel="B" itemValue="b" />
    <f:ajax event="change" listener="#{beanName.actionMethodToNavigate}" onevent="function(data){clickToNavigate(data, '#{beanName.tempValue}')}"/>
</h:selectOneMenu>

<script>
    function clickToNavigate(data, value){
        if(data.status=="success"){
            if (value=='0'){ 
                return false;
            } else if (value=='a'){
                 jumpToAhchor('#listItems');
                 return false;
            }
        }
    }
</script>
01000001
  • 833
  • 3
  • 8
  • 21