Combo does not load with call via jquery

1

I'm trying to fill a dropdown menu which, when the torina is put on a button this works.

But since I want this padding to happen automatically as soon as the document is loaded, I jQuery.ready () for this, however, the function it invokes does not work, ie the menu is not being populated.

Current code:

function PreencheCombo() {

    var str = "";

    $.ajax({
        url: '/Cadastro/PreencheComboUf',
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        success: function (data) {
            str += '<label for="cbxUf" class="col-sm-4 control-label">UF</label>';
            str += '<select class="form-control col-sm-4" name="cbxUf" id="cbxUf">';
            $(data.result_combo).each(function () {
                str += '<option value=' + this.sigla + '>' + this.descricao + '</option>';
            })
            str += '</select>';

            $('#combo').html(str);
        },
        error: function (error) {
        }
    })
}

And the invocation:

$(document).ready(function () {
    PreencheCombo();
});

If I put a button to call the FillCombo function there, then it's ready that is not working.

    
asked by anonymous 29.07.2014 / 15:55

2 answers

2

I solved it like this:

window.onload = function () {
    PreencheCombo();
}
    
29.07.2014 / 16:10
2

It's good that you have solved the problem on your own, but I believe that a better explanation of why this happens is valid.

Event ready occurs after that the HTML document loads, whereas the onload Event occurs later, after all content (such as images) already been.

The onload Event is a Default Event in the DOM, while Event ready is specific to jQuery. The purpose of the ready event is to occur as soon as the document is loaded, so codes that add functionality to the page elements do not have to wait for all elements to be created in the DOM.

In your case, you invoked the function in ready expecting the dropdown to be populated, but since ready is triggered even before the DOM has been completely populated, the dropdown does not yet exist to be populated.     

29.07.2014 / 16:29