2011-04-20 85 views
0

我有用JQuery生成的下拉(選擇)菜單,動態使用來自PHP腳本的JSON。 請參閱附件中的圖片,在組件標籤下。 「選擇」菜單包含組件名稱和組件ID(值)。 example更改JQuery動態下拉菜單填充其他字段

我想要使用JQuery的「更改」事件來填充以下字段代碼,類別和UOM,以及相應的值。

我的JSON對象檢索所需的一切(我設法用JQuery自動完成來實現這一點)。

例如。

[{"id":"4","component":"Component 1","code":"COMP1","uom":"kilo","category":"Flour"}...] 

這是我的代碼,用於生成「選擇」菜單,其中包含來自上述JSON的選項。

$.getJSON("<?php echo site_url('products/dropdown/no'); ?>", function(result) { 
      var optionsValues = '<select>'; 
      optionsValues += '<option value="">' + '--' + '</option>'; 
      $.each(result, function() { 
      optionsValues += '<option value="' + this.id + '">' + this.component + '</option>'; 
      }); 
      optionsValues += '</select>'; 
      var options = $("select[name=component]"); 
      options.replaceWith(optionsValues); 
     }); 

它位於$(document).ready中。

所以,我需要功能或者什麼東西,只要在「選擇」菜單發生變化時,它就會用相應的值填充所提到的字段。

非常感謝您提前。

回答

4
$('select').change(function(){ 
    //Populate other fields 
    //$.getJSON() 
    //$('input.code').val(response.code) 
    //etc... 
}); 

或者,如果你生成的選擇元素在頁面加載後,您可以使用:

$('select').live('change', function(){ 
    //Populate other fields 
}); 
+0

如何指的是與所選擇的下拉值對應的那些特定的值(代碼,類別,計量單位)? – 2011-04-21 13:00:37

+0

在你的getJSON函數中,你可以使用result.code,result.category等獲取你的php腳本中的值,然後你必須使用$('input [name = code]').val(result.code)或者無論什麼領域被稱爲添加它。 – Calum 2011-04-21 20:56:45

0
$("#select").change(function(){ 


}); 
0

這是怎麼回事我做的工作:

填充選擇元素,並將結果存儲在JSONObject變量中:

$.getJSON("http://localhost/ci/index.php/products/dropdown/no", function(result) { 
    var optionsValues = "<select id='component'>"; 
    JSONObject = result; 
    optionsValues += '<option value="">' + '--' + '</option>'; 
    $.each(result, function() { 
      optionsValues += '<option value="' + this.id + '">' + this.prodname + '</option>'; 
    }); 
    optionsValues += '</select>'; 
    var options = $("select#component"); 
    options.replaceWith(optionsValues); 
}); 

當用戶改變這些值在選擇菜單:

$("select#component").live('change',function() { 
      if(this.selectedIndex == '') 
      { 
       $("input#code").val(''); 
       $("input#category").val(''); 
       $("input#uom").val(''); 
       return false; 
      } 
      $("input#code").val(JSONObject[this.selectedIndex-1].code); 
      $("input#category").val(JSONObject[this.selectedIndex-1].pcname); 
      $("input#uom").val(JSONObject[this.selectedIndex-1].uname); 
     }); 
相關問題