2015-02-23 20 views
1

我有下面的代碼的PHP Zend下拉列表:如何在JavaScript中動態獲取下拉值?

$this->addElement('select', 'target', array(
      'decorators' => $this->getElementDecorators(), 
      'label' => Zend_Registry::get('Zend_Translate')->translate('Target_Platform'), 
      'style' => 'width:320px;', 
      'data-help' => Zend_Registry::get('Zend_Translate')->translate('Target_Platform_To_Publish_To'), 
     )); 

這有大約14值的列表。

我使用下面的代碼在我的JS文件,以獲得當前下拉值:

this.temp = $('#target :selected').text(); 
console.dir(this.temp); 

然而,當我選擇下拉一些其他的價值在這個變量的值沒有變化? 我希望變量根據用戶選擇的值動態更改

這怎麼可能? 感謝您的閱讀:)

回答

0

您可以使用.select事件來做到這一點。

$(document).ready(function(){ 

    $("#target").select(function(){ 

     console.log($(this).val()); 

    }); 

}); 

,我希望你已經包括jQuery文件

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 

編輯

<body> 

..... 
// At the end of the body because JS loads Synchronously 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
</script> 
$(document).ready(function(){ 

     $("#target").select(function(){ 

      console.log($(this).val()); 

     }); 

    }); 
</script> 

</body> 
+0

Thanks Void。 我在哪裏添加腳本標籤? 在JS文件中? – ggwp 2015-02-23 07:28:24

+0

正好在$(document).ready()之上; – void 2015-02-23 07:29:38

+0

查看更新的答案。 – void 2015-02-23 07:31:04

0

這個工作。

$('#target').on('change', function() { 
     var data = { 
     platform: $('#target :selected').text() 
     }; 
     console.log(data); 
0

嘗試綁定this.temp = $('#target :selected').text();某些事件(.select),所以當事件被觸發時,所需的代碼將被執行。從目前的方法來看,this.temp = $('#target :selected').text();只有在文檔加載時纔會執行,並給出默認值。

http://api.jquery.com/category/events/