2015-11-08 79 views
2

我已經寫了下面的代碼,生成一個選擇列表。然而,它應該檢查this.id是否等於與existing_code相同並將選定值放入的部分似乎不起作用。javascript foreach選擇循環與選定的值

任何想法是什麼錯?

function showHide(layer, existing_code) { 

jQuery.ajax({ url: 'getdata.php', dataType: 'json', cache: 'false', success: function(data) { 

    var codes = codes; 
    var selectcode = ''; 

    selectcode += '<select name="codes">'; 
     jQuery.each(codes, function() { 
      selectcode += '<option value="' + this.id + '"'; 
       if (this.id == existing_code) { 
        selectcode += ' selected'; 
       } 
      selectcode += '>' + this.code + '</option>'; 
     }); 
    selectcode += '</select>'; 

    jQuery('.'+layer).html(selectcode); 

}}); 

} 
+2

'VAR碼=碼;' - 嗯,這不是非常有用的,它是......你也沒有「 '元素 - 從ajax返回的'data'也被忽略,所以,不知道你期望什麼 –

回答

0

這可能是你想要什麼:

function showHide(layer, existing_code) { 

    jQuery.ajax({ url: 'getdata.php', dataType: 'json', cache: 'false', success: function(data) { 

     var codes = data; 
     var selectcode = ''; 

     selectcode += '<select name="codes">'; 
     jQuery.each(codes, function(i, code) { 
      selectcode += '<option value="' + code.id + '"'; 
      if (code.id === existing_code) { 
       selectcode += ' selected'; 
      } 
      selectcode += '>' + code.code + '</option>'; 
     }); 
     selectcode += '</select>'; 

     jQuery('.'+layer).html(selectcode); 

    }}); 

}