Search code examples
javascriptarrayscomboboxxpagesxpages-ssjs

Programmatically Select Combobox Value


I have a combobox on an xPage that is populated via a JavaScript file.

This xPage also has a postNewDocument event that calls a LotusScript agent which pre-populates most of the fields on the xPage from the in-memory document, which works for all but this type of field, since the values of the combobox aren't populated until the JavaScript file is called for that field.

The most efficient way I can see to select the combobox entry from the in-memory document, is to put the value from the document into a text field, and then read it from that field. Here is what's in the Values field of the combobox:

var rArray = getItemOptions();
var prevCountry = getComponent("Org_Country").getValue();
var opt;
if ((prevCountry != "") && (prevCountry != null)){
  for (var i=0; i < rArray.length; i++) {
    rArray[i];
    opt = rArray[i];                    
    if (opt.contains(prevCountry)) {        
        rArray.selectedIndex = i;
    }
  }
}
return rArray;

And here's what a bit of the source code looks like:

<option value="1">Afghanistan</option>
<option value="2">Albania</option>
<option value="3">Algeria</option>
<option value="4">American Samoa</option>

What I believe I need to do is set selected="selected" but there are no "options" in rArray. I've tried other variations such as rArray[i].selected = true and rArray[i].selected = "selected" and they don't produce errors, but just produce the whole combobox.

I want to have the previously selected combobox item selected, but leave it in the same position in the combobox and allow the user to change their selection.

Here is the markup for my combobox:

<xp:comboBox id="Country" value="#{document1.Country}" styleClass="form-control">
   <xp:selectItems>
       <xp:this.value><![CDATA[#{javascript:return getItemOptions();}]]> </xp:this.value>
   </xp:selectItems>
    <xp:eventHandler event="onchange" submit="true" refreshMode="partial"
    disableValidators="true"
    refreshId="Province">
    <xp:this.action><![CDATA[#{javascript:var selected = getComponent("Country").value;
viewScope.put("countrySelected", selected);}]]></xp:this.action>
    <xp:this.onComplete><![CDATA[$("form").formValidation("addField", "#{id:Province}");
]]></xp:this.onComplete>
    </xp:eventHandler>
</xp:comboBox>

What I have started on now is putting this code in the onClientLoad event, but I haven't gotten it to work.

The numbers for the countries have come from a database I obtained elsewhere but I can change them.


Solution

  • I figured out how to do this. Because I didn't have the value, I just ran a modified version of the function that populates the combobox, returning the value as my default and it's all good. I was overthinking this.

    I will follow @stwissel's suggestion to use the ISO codes.