treyBake
treyBake

Reputation: 6560

Create a variable to equal a dynamically created DOM element

I'm working on a function:

var container      = $('#container'),
    line1          = $('#line1'),
    line2          = $('#line2'),
    line3          = $('#line3'),
    line4          = $('#line4'),
    postcode       = $('#postcode'),
    addressPicker  = $('#selector'),
    noneOfTheAbove = $('#noneOfTheAbove');

    $(document).on('click', '#noneOfTheAbove', function()
    {
        container.removeClass('hidden');

        noneOfTheAbove.addClass('noDisplayElementImportant');
        addressPicker.addClass('hidden');

        line1.val('');
        line2.val('');
        line3.val('');
        line4.val('');
        postcode.val('');
    });

The only problem with this is the DOM gets dynamically created on a button click. So using the variables like this doesn't work becuase on $(document).ready() they don't exist. How can I assign dynamic DOM elements to a variable? Would it be something like $(document).find('#idHere')?

Thanks

UPDATE 1

making vars global then local (using charlietfl answer):

var container,
    line1,
    line2,
    line3,
    line4,
    postcode,
    addressPicker,
    noneOfTheAbove;

 $(document).on('click', '#noneOfTheAbove', function()
 {
     container      = $('#container');
     line1          = $('#line1');
     line2          = $('#line2');
     line3          = $('#line3');
     line4          = $('#line4');
     postcode       = $('#postcode');
     addressPicker  = $('#selector');
     noneOfTheAbove = $('#noneOfTheAbove');

     container.removeClass('hidden');

     noneOfTheAbove.addClass('noDisplayElementImportant');
     addressPicker.addClass('hidden');

     line1.val('');
     line2.val('');
     line3.val('');
     line4.val('');
     postcode.val('');
});

Upvotes: 1

Views: 61

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Define those variables inside the event handler when they do exist

$(document).on('click', '#noneOfTheAbove', function() {

  var container = $('#container'),
    line1 = $('#line1'),
    line2 = $('#line2'),
    line3 = $('#line3'),
    line4 = $('#line4'),
    postcode = $('#postcode'),
    addressPicker = $('#selector'),
    noneOfTheAbove = $('#noneOfTheAbove');
  container.removeClass('hidden');

  noneOfTheAbove.addClass('noDisplayElementImportant');
  addressPicker.addClass('hidden');

  line1.val('');
  line2.val('');
  line3.val('');
  line4.val('');
  postcode.val('');
});

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Do not eager load them as they are dynamic. Go with lazy loading which means that use them when you require them.

    var container,
    line1,line,.. ;
    $(document).on('click', '#noneOfTheAbove', function()
        {  
            container = $('#container');
            container.removeClass('hidden');

            ... // others

            ...
        });

Upvotes: 1

Related Questions