Command button in Visualforce can't read selected item from dynamic drop down list

左心房为你撑大大i 提交于 2019-12-11 18:21:35

问题


I am looking for help from Visualforce (Salesforce) page guru.

Background: There is a drop down list (apex:selectList in terms of Visualforce page). Its select options are built by jQuery with returned data (in JSON format) from RemoteAction (in Controller).

Problem: it always reports error message (j_id0:j_id2:j_id3:j_id4:orgList: Validation Error: Value is not valid) when I click command button which sends selected item value to Controller.

Any thoughts? Thanks very much.

Troy

Visualforce markup:

<apex:panelGrid columns="2">
<apex:selectList id="orgList" value="{!selected}"  size="1">
</apex:selectList>
<apex:commandButton value="Add" action="{!add}" style="width:80px">
</apex:panelGrid>

JavaScript:

$j("input[id$='azc']").keyup(function(){
   var op = $j("select[id$=orgList]");
    if($j(this).val().length >= 6){
             op.empty().append('<option value=""></option>');
             OrgController.findOrgs($j(this).val(), function(result, event){
                  if(event.status){
                      var data =  $j.parseJSON('[' + result.replace(/'/g, '"') + ']');
                      $j.each(data, function(){
                          $j('<option />', {value: this['value'], text: this['label']}).appendTo(op);
                      }); 
                  }else{
                      alert(event.message);             
                  } 
              },{escape:true});
        } 

OrgController

public String selected { get; set; }
public PageReference add(){
    Customer__c customer =  findSelected(selected);
    if(customer != null){
      customer.Pending__c = 'Yes';
      update customer; 
    }
    return null;
}

回答1:


I would try to use a normal (html) select list and send selected value to controller per hidden field like this (works for me):

<!-- If the user selects an option - we will fill out the hidden field with that value -->
<select size="1" id="orgList" onChange="jQuery('[id$=hiddenField]').val(document.getElementById(this.id).value);">
    <option value="none">--Please select--</option>
</select>

<!-- Now add new options -->
<script>
    var myOptions = {
        val2 : 'Val 2',
        val3 : 'Val 3'
    };

    var mySelect = jQuery('#orgList');

    jQuery.each(myOptions, function(val, text) {
        mySelect.append( jQuery('<option></option>').val(val).html(text) );
    });

</script>

<!-- Here is the hidden field assigned to the apex variable -->
<apex:inputHidden value="{!myselected}" id="hiddenField"/>

<apex:commandButton reRender="none" value="Get value"/>


来源:https://stackoverflow.com/questions/11989585/command-button-in-visualforce-cant-read-selected-item-from-dynamic-drop-down-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!