问题
I have a PrimeFaces 5.1 <p:selectOneMenu>
that generates in DOM the following select:
<select id="WorkSpace:test:selectYear_input"
name="WorkSpace:test:selectYear_input" tabindex="-1">
<option value="" selected="selected">-- Year --</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
I have a <p:commandButton>
that triggers a jQuery function that will handle changing my <p:selectOneMenu>
.
<p:commandButton onclick="changeDropDownList();" />
jQuery function:
function changeDropDownList()
{
$('[id$=selectYear_input]')[0].selectedIndex = 2;
}
The <p:selectOneMenu>
is not updated. How is this caused and how can I solve it?
回答1:
The <p:selectOneMenu>
is basically a <div><ul><li>
layer over <select><option>
which is visually hidden. Any changes to <select><option>
in the DOM is not reflected in the <div><ul><li>
. It happens only the other way round.
It has however a bunch of event listeners attached which should be reflected back in the hidden <select><option>
. One way is triggering the click
event on the .ui-selectonemenu-item
of interest in the menu's panel.
Given a
<p:selectOneMenu widgetVar="selectYear">
You could select the 3rd item in jQuery as below
PF("selectYear").panel.find(".ui-selectonemenu-item:eq(2)").click();
Alternatively, you could also just do it via <p:ajax>
(which under the covers ultimately uses jQuery's $.ajax()):
<p:selectOneMenu id="selectYear" value="#{bean.selectYear}">
...
</p:selectOneMenu>
...
<p:commandButton ...>
<p:ajax listener="#{bean.setSelectYear(2014)}" update="selectYear" />
</p:commandButton>
It's only a small roundtrip.
回答2:
According to PF documentation from 3.4 to 5.1, if you assign the widgetVar attribute on the p:selectOneMenu, you can call selectValue(value) on the widget.
This does select the specified value, but presumes that you know the target value string and case.
It does not work with numerical index.
来源:https://stackoverflow.com/questions/29657946/change-item-of-pselectonemenu-using-jquery