Combo does not load with calling via jquery

Asked

Viewed 149 times

1

I’m trying to fill a dropdown menu that when Torina is placed on a button this works.

But since I want this fill-in to happen automatically as soon as the document is loaded into jQuery.ready() for this, however, the function invoked in it does not work, that is, the menu is not being filled.

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 function Filler then it works, so it is the ready that is not working.

  • It’s not clear what you’re asking... gift??

  • I made an edit and switched to document

2 answers

2

I resolved so:

window.onload = function () {
    PreencheCombo();
}

2

I’m glad you solved the problem on your own, but I believe a better explanation of why it happens is valid.

The Event ready occurs afterward that the HTML document is loaded while the Event onload occurs later, after all content (such as images) has also been.

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

In your case, you invoked the function on ready waiting for the dropdown to be filled, but like the ready is fired even before the DOM has been fully filled, the dropdown still does not exist to pder be populated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.