skaarj
skaarj

Reputation: 100

jquery trigger button click, and get value of dynamic select/option

I am trying to get 'value' of dynamically generated < option > on button click, it works when I physically press button but when I call: $("#view").trigger('click'); all I get is undefined

EDIT: Updated code

<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">
</script>
</head>

<body>

<script>
    $(document).ready(function() {
        var placeholder = $("#test");

        var yearList = $("<select />", {'class': 'form-sth', 'id': 'year-list'});
        var weekList = $("<select />", {'class': 'form-sth', 'id': 'week-list'});
        var fileList = $("<select />", {'class': 'form-sth', 'id': 'file-list'});

        var viewButton = $("<button />", {'class': 'btn btn-default', 'id': 'view', 'text': 'view'});

        function populate(list, base_dir, prefix, postfix, bFiles) {
            $.ajax({
                url: 'stat.php',
                type: 'GET',
                data: { dir: base_dir, files: (bFiles == true) ? '1' : '0' },
                dataType: 'json',
                success: function(json) {                   
                    json.content.forEach(function(entry) {
                        var option = $("<option />", {'value': prefix + entry + postfix, 'text': entry} );

                        list.append(option);
                    });

                    var lastOption = list.children('option:last-child');

                    lastOption.attr('selected', 'selected');
                    lastOption.trigger('change');
                }
            })
        }

        var baseDir = '/var/www/_cronjob/data/ups-stats/';

        populate(yearList, baseDir, '', '/', false);

        yearList.on('change', function() {
            console.log('#year-list : onChange()');

            var selectedOption = $('#year-list option:selected');

            populate(weekList, baseDir + selectedOption.attr('value'), selectedOption.attr('value'), '/', false);
        })

        weekList.on('change', function() {
            console.log('#week-list : onChange()');

            var selectedOption = $('#week-list option:selected');

            populate(fileList, baseDir + selectedOption.attr('value'), selectedOption.attr('value'), '', true);
        })

        var delay = 1500;

        yearList.appendTo(placeholder).hide().fadeIn(delay);
        weekList.appendTo(placeholder).hide().fadeIn(delay);
        fileList.appendTo(placeholder).hide().fadeIn(delay);
        viewButton.appendTo(placeholder).hide().fadeIn(delay);

        viewButton.on('click', function() {
            console.log('#view : onClick()');
            var option = $('#file-list option:selected');

            console.log(baseDir + option.attr('value'));
        })

        console.log('button click! ...');
        $("#view").trigger("click");
    });

</script>

<div id="test">
</div>

</body>

</html>

Example output of stat.php?dir=/var/www/&files=1

{"content":["index.php","test.php"]}

I don't understand this, could someone please explain why is this happening and how to solve this?

EDIT: I have placed many console.log() functions to trace what is going on and I have figured that code that generates < options > is executed after I simulate button click.

Details: I have 3 < select > lists. first contains year folders, second: week folders and third: file names. At the begining I am loading 'year' folders and then it's something like chain reaciton: onChange() function of each < select > is loading data for next < select >

https://i.sstatic.net/rlUwY.png

Upvotes: 1

Views: 1996

Answers (2)

skaarj
skaarj

Reputation: 100

I solved my problem, I had to put viewButton.trigger('click'); in complete callback of $.ajax

Upvotes: 0

Hackerman
Hackerman

Reputation: 12295

Working code:

$(function(){
 var placeholder = $("#test");

 var fileList = $("<select />", {'id': 'file-list'});
 var viewButton = $("<button />", {'id': 'view', 'text': 'view'});

 // ... here is the code that generates <options> ...

 var delay = 1500;
 fileList.html('<option value="1">Uno</option><option value="2">Dos</option>');
 fileList.appendTo(placeholder).hide().fadeIn(delay);
 viewButton.appendTo(placeholder).hide().fadeIn(delay);

 viewButton.on('click', function() {
   var option = $('#file-list option:selected').text();

   console.log(option);
 })

 viewButton.trigger('click');  // here i get 'undefined'
});

Working fiddle: http://jsfiddle.net/xwcnvvar/

PS: You need to include your code when the DOM is generated; if you don't do that, when you try to bind a function to a non existent element you get an undefined like error. In your case you have the select element, but you have no options, so nothing get selected(that's why i add two options on your code) Cheers :)

Upvotes: 1

Related Questions