简体   繁体   中英

How to get drop down value dynamically in JavaScript?

I have a dropdown list in PHP Zend with the following code :

$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'),
        ));

This has a list of about 14 values.

I am using below code in my JS file to get the CURRENT drop-down value :

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

However the value in this variable does not changes when I select some other value in the dropdown ? I want the variable to change dynamically as per the values selected by the user.

How is that possible ? Thanks for reading :)

You can use .select event to do this.

$(document).ready(function(){

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

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

    });

});

And i hope that you have included jQuery file

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

EDIT

<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>

This worked .

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

Try binding this.temp = $('#target :selected').text(); to some event( .select ), So when event get fired the desired code will get executed. From current approach , this.temp = $('#target :selected').text(); will get executed only when the document is loaded giving the default value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM