0

I have following selectOneMenu

<p:selectOneMenu value="#{bean.value}">
    <f:selectItem value="#{bean.item1}"/>
    <f:selectItem value="#{bean.item2}"/>
    <f:selectItem value="#{bean.item3}"/>

    <p:ajax listener="#{bean.item3AjaxEvent}" update="fieldToUpdate"></p:ajax>

</p:selectOneMenu>

Now I want to do some AJAX action only when item3 is selected from selectOneMenu. Not for all the items. Is there any way of doing that?

Putting ajax tag will fire the event for all the select items. I don't want to generate unwanted ajax requests to server.

Aqeel Ashiq
  • 1,988
  • 5
  • 24
  • 57
  • describe your AJAX action ? What does it mean ? – Makky Feb 18 '14 at 14:24
  • @Makky I have edited code in my question. Please have another look. – Aqeel Ashiq Feb 18 '14 at 14:30
  • `p:ajax` has a `onstart` attribute. Check your condition and try returning false from that function to stop execution. – mabi Feb 18 '14 at 14:32
  • @djaqeel simply in your item3AjaxEvent method check for selecgted value . if it is item3 then do your business login otherwise just return. – Makky Feb 18 '14 at 14:33
  • @mabi returning false would not stop the ajax request. it's called onstart, it means it's already started – Hatem Alimam Feb 18 '14 at 14:41
  • @HatemAlimam I'll defer to optimus.prime [saying](http://forum.primefaces.org/viewtopic.php?f=3&t=17014#p51899): "Try returning false on start." – mabi Feb 18 '14 at 14:55
  • Have you tried it ?.. I have just tried it and it didn't work, ajax request fired anyway ! @mabi – Hatem Alimam Feb 18 '14 at 15:02
  • @HatemAlimam lacking a primefaces environment here. I'll have to take the word of [many](http://forum.primefaces.org/viewtopic.php?f=3&t=1792) [users](http://wrschneider.blogspot.de/2012/01/primefaces-ajax-callbacks-onstart-vs.html) [around the internet](http://cagataycivici.wordpress.com/2010/08/12/primefaces-ajax-callbacks/). YMMV. – mabi Feb 18 '14 at 15:20
  • @mabi well it seems legit, and I remember now that I have used this before in an ajax inside a command button and it worked ... well maybe this time didn't work for some reason in my environment... thanks – Hatem Alimam Feb 18 '14 at 15:22

1 Answers1

1

I would do it in this way.

xhtml

 <p:selectOneMenu widgetVar="selectOneMenuWV"
                  onchange="checkItem()">  
   <f:selectItem itemLabel="Select One" itemValue="" />  
   <f:selectItem itemLabel="Option 1" itemValue="1" />  
   <f:selectItem itemLabel="Option 2" itemValue="2" />  
   <f:selectItem itemLabel="Option 3" itemValue="3" />                             
 </p:selectOneMenu> 


<p:remoteCommand name="myRemoteCommand" 
             actionListener="#{bean.item3AjaxEvent()}"  
             update="fieldToUpdate"/>

<script>
    function checkItem() {
       if(selectOneMenuWV.getSelectedValue() == 3) {
            myRemoteCommand();
       }
    }
</script>

Hope this helps.

Hatem Alimam
  • 9,968
  • 4
  • 44
  • 56