Skip to content Skip to sidebar Skip to footer

Selecting An Option On A Dynamically-populated Select Element In Jquery/ajax

I have a dynamically-populated select box which is intended to be used for displaying information about a single option. The problem I've got is that it doesn't seem to fire a :sel

Solution 1:

Replacing the HTML of a select element dynamically is bound to cause problems. It is best to use JavaScript itself in order to let the browser properly handle it. Click here to see how

Solution 2:

Use the onclick event and then get the selected value by using the following

<selectid="activeList"size="5"onclick='onclicklist()'></select><script>functiononclicklist() {
        var selectedvalue = $("#activelist option:selected").val();
    }
</script>

Solution 3:

First, some browsers don't respond well to having a select node populated with .html(...). It's far safer to append option nodes.

Second, to respond to user selections of the populated select element, you need to attach an 'onchange' handler. The attachment can be made before or after the options have been added.

functionpopuList() {
    var $select = $("#activeList").on('change', function() {
        var val = this.value;
        //do real kewl stuff with the value here
    });
    // Populates the SELECT element with options from the JSON file.var url = "/calls/sessions.php";
    $.getJSON(url, '', function(jdata, oSucc, jqXHR){
        $.each(jdata,function(i, session) {
            $.each(session, function(n, data) {
                $('<option value="' + data.name + '">' + data.name + '</option>').appendTo($select);
            });
        });
    });
}

Post a Comment for "Selecting An Option On A Dynamically-populated Select Element In Jquery/ajax"