I'm trying to pre-select the country of user in a selectOneMenu using javascript. The problem is that when the page initially loads the list is still on the first element. However if I click on the arrow to expand the list, and then click somewhere else on the page to make the list disappear, then the value is the one set by javascript.
<p:selectOneMenu styleClass="inputField selectOneMenuColored" required="true" editable="false" id="country" value="#{subscribeUser.user.countryBean}" converter="#{countriesConverter}" effect="fold">
<f:selectItems value="#{countriesConverter.countries}" var="country" itemLabel="#{country.shortName}" itemValue="#{country}" />
</p:selectOneMenu>
and the javascript:
<script language="JavaScript" src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>
<h:body id="whole" onload="setSelectedIndex('form:country_input',geoplugin_countryName());">
...
function setSelectedIndex(menuId, val){
var menu = document.getElementById(menuId);
var opts = menu.options;
for( j = 0; j < opts.length; j++) {
if(opts[j].value == val) {
opts[j].selected= "true";
}
}
}
Hatem Alimam
I'm not sure what's the goal but the answer is this:
Select by value:
PF('selectOneMenuWV').selectValue('3')
Select by label:
PF('selectOneMenuWV').selectItem(PF('selectOneMenuWV').jq.find('.ui-selectonemenu-item[data-label*="Option Label"]'))
Note that you should define a widgetVar, which is selectOneMenuWV in this example.
<p:selectOneMenu ... widgetVar="selectOneMenuWV">
来源:https://stackoverflow.com/questions/31866658/selecting-option-in-pselectonemenu-using-js