jQuery Defines a global variable for an element that does not yet exist in DOM


I'm working on a page where user can create a form by clicking to insert fields. Initially no input elements exist on the page. User clicks to created them. I'm trying to create Global variables to reference those input fields so i can later make use of this, but since input fields do not initially exist in DOM, the global variable is giving undefined. Anyway way around this. I want the variables to be global, because i want to make use of them in other functions.


var $selected = $('#form').find('.selected input').val(); //Global variable outside the function. Since this doesn't initially exist in DOM, it's giving undefined.

You can reference the same variables everywhere. However, the catch being that since the DOM is initially empty, you have to populate those variables when a user creates these objects.

var $selected;

Say when the user clicked a button to insert an input element. The $selected variable has to be updated at this time.

function addTextInput() {
    var input = $('<input type="text" value="awesome" />');
    $("form .selected").append(input);

    // the global variable is being updated now.
    $selected = $('#form .selected input').val();