Search code examples
jquerypropertiesready

Why jQuery doesn't find an element in ready event?


I defined object of CgridAdminView with the properties and methods:

var CgridAdminView = {
    controller_name: 'work',
    div_table_id: 'grid-admin-works',
    tr_add: $('#' + this.div_table_id).find('tr').eq(1),
    disabled: '.td_workGroup',
    list_cols: [
        'index',
        'shortName',
        'fullName',
        'codeName',
        'workGroup_id',
        'period',
        'performers']
};

tr_add property doesn't contain elements in the processor of an event of ready:

$(function(){
    CgridAdminView.tr_add.hide();
});

It is works:

$(function(){
     var tr_add = $('#'+CgridAdminView.div_table_id).find('tr').eq(1);
     tr_add.hide();
});

But tr_add property contains the necessary element in methods of object of CgridAdminView.

In what error?


Solution

  • Looks like you are not declaring CgridAdminView inside a dom ready handler

    $(function () {
    
        var CgridAdminView = {
            controller_name: 'work',
            div_table_id: 'grid-admin-works',
            tr_add: $('#' + this.div_table_id).find('tr').eq(1),
            disabled: '.td_workGroup',
            list_cols: [
                'index',
                'shortName',
                'fullName',
                'codeName',
                'workGroup_id',
                'period',
                'performers']
        };
        CgridAdminView.tr_add.hide();
    })
    

    Because the tr_add properties value is assigned when CgridAdminView is created, so when the object is create if the target element is not loaded then the evaluation of $('#' + this.div_table_id).find('tr').eq(1) will not return any result.

    The main point is the jQuery selector need to happen in dom ready