2016-02-05 58 views
-5

此代碼:的jQuery選擇選項的值返回NULL

$("#host_select").val($("#host_select option:first").val()); 
alert($("#host_select").val()); 

警報空。但是在host_select中有一些有值的選項。什麼可能是錯的?

+0

代碼是巨大的。除了這部分,一切都很好。 –

+0

只顯示你的drop drop淹沒代碼.. –

+0

json查詢更新的數據:

回答

0

你可以做更多的研究,關於JavaScript和HTML

這裏有一個例子:

https://fiddle.jshell.net/v4rwxz1q/

HTML:

<select name="" id="host_select"> 
    <option value="1">first</option> 
    <option value="2">second</option> 
</select> 

JS:

var first = $("option:first", "#host_select").val(); 
alert(first) 

希望能讓你有個好開始

0

我猜,我發現了。問題在於,在填充選擇輸入後你無法獲得選定的值。

$('#location_select').change(function() 
     var sel=$("#location_select").val(); 

這裏sel將爲空。那是因爲此時瀏覽器還沒有完全做出選擇。 所以我用setTimeout來等待選擇完成。

0
<html> 
<head> 
<script src="http://code.jquery.com/jquery-1.10.2.js"></script> 

<script> 
    $(document).ready(function() { 

     var newOptions = { 
      "Option 1": "value1", 
      "Option 2": "value2", 
      "Option 3": "value3" 
     }; 

     var $el = $("#host_select"); 
     $el.empty(); // remove old options 
     $.each(newOptions, function (value, key) { 
      $el.append($("<option></option>") 
       .attr("value", value).text(key)); 
     }); 


     // First 
     $("#host_select").val($("#host_select option:first").val()); 

     alert($("#host_select").val()); 

     //Second 
     $("#host_select").val($("#host_select option:eq(1)").val()); 

     alert($("#host_select").val()); 

     //third 
     $("#host_select").val($("#host_select option:eq(2)").val()); 

     alert($("#host_select").val()); 

    }); 
</script> 
</head> 
<body> 
    <select class="form-control" id="host_select"></select> 
</body> 
</html>