0

I have been developing a web-wizard type form that uses a single page to ask questions, changing the content shown in a div, with various pre-populated selects, input texts, a date picker, some of the WIZ data comes back form the server as a result of selections. The wiz stores all it's "stuff" in the WIZ array locally, eventually I'll likely transition to using the server session to store the stuff, but for now it's working, mostly.

I have come to an impasse in that data I'm trying to glean from some dynamically generated form elements is inaccessible and returns 'undefined'. I can't figure out why

I suspect, because the "savespawntask" sequence and the response does show that valid json was received and forwarded that the sequence does in fact serialise a forms data and does work if I have it use a static form that was an element present when the page originally loaded. Its anything I've appended after seems to be inaccessible

var wiz_numpages = 9;
var wiz_currentpage = 0;
var wiznav_buttons_next="<button id=\"wiznav_next\">Next</button>";
var wiznav_buttons_prev="<button id=\"wiznav_prev\">Previous</button>";
var wiznav_buttons_accept="<button id=\"wiznav_accept\">Accept Target Solution</button>";
var wiznav_buttons_propose="<button id=\"wiznav_propose\">Propose Target Solution</button>";
var wiznav_buttons_addmtl="<button id=\"wiznav_addmtl\">Add Timeline Entry</button>";
var wiznav_buttons_addsmtl="<button id=\"wiznav_addsmtl\">Add Spawn Timeline Entry</button>";
var wiznav_buttons_savespawntasks="<button id=\"wiznav_savespawntasks\">Save as template</button>";
var wiznav_buttons_savesubstratetasks="<button id=\"wiznav_savesubstratetasks\">Save as template</button>";

var WIZ = new Array();
var wiz_loading_img = "<img class=\"wiz_loading_img\" src=\"images/loading.gif\" />";
$(document).ready(function(){
console.log("Wizard starting...");
wiz_start();
});

async function wiz_start(){
wiz_showpage(wiz_currentpage);
}

function wiz_showpage(thiswizpage){
wiz_showloading();
wiz_shownav(thiswizpage);
setTimeout(wiz_getcontent,2000,thiswizpage);
}

function wiz_shownav(thiswizpage){
if(thiswizpage==0){
    $('#wiz_nav_left').html("");
    $('#wiz_nav_right').html(wiznav_buttons_next);
    $('#wiznav_next').on('click',function(){wiznav_next();});
}else if(thiswizpage == wiz_numpages - 1){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_propose);
    $('#wiznav_propose').on('click',function(){wiznav_propose();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(null);});
}else if(thiswizpage == wiz_numpages){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_accept);
    $('#wiznav_accept').on('click',function(){wiznav_accept();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);});
}else if(thiswizpage == 99){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_addmtl);
    $('#wiznav_addmtl').on('click',function(){wiznav_addmtl();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);}); 
}else if(thiswizpage == 100){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_addsmtl);
    $('#wiznav_addsmtl').on('click',function(){wiznav_addsmtl();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);}); 
}else if(thiswizpage == 101){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html("");
    //$('#wiznav_savespawntasks').on('click',function(){wiznav_savespawntasks();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);}); 
}else if(thiswizpage == 102){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html("");
    $('#wiznav_savesubstratetasks').on('click',function(){wiznav_savesubstratetasks();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);}); 
}else if(thiswizpage == 103){
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_savespawntasks);
    $('#wiznav_savespawntasks').on('click',function(){wiznav_savespawntasks();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(wiz_numpages-1);}); 
}else{
    $('#wiz_nav_left').html(wiznav_buttons_prev);
    $('#wiz_nav_right').html(wiznav_buttons_next);
    $('#wiznav_next').on('click',function(){wiznav_next();});
    $('#wiznav_prev').on('click',function(){wiznav_prev(null);});
}
}

function wiznav_next(){
wiz_currentpage++;
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">getting next step...</h1>").hide().fadeIn(500);
console.log("next clicked set cp:" + wiz_currentpage);
wiz_showpage(wiz_currentpage);
wiz_shownav(wiz_currentpage);
}
function wiznav_prev(thispage){
var pagetoset=null;
wiz_currentpage--;
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">getting previous step...</h1>").hide().fadeIn(500);
console.log("prev clicked set cp:" + wiz_currentpage);
if(thispage!=null){pagetoset=thispage;}else{pagetoset=wiz_currentpage}
wiz_showpage(pagetoset);
wiz_shownav(pagetoset);
}

function wiz_showloading(){
$('#wiz_main').html(wiz_loading_img);
}
function wiznav_propose(){
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">calculating proposal...</h1>").hide().fadeIn(500);
wiz_showloading();
wiz_currentpage++;
wiz_getpropose();
wiz_shownav(wiz_numpages);
}
function wiznav_accept(){
    if(wiznav_alertConfirmation("Adding a target is serious business!\nAre you sure you want to do that?!")){
    wiz_accept();
    }else{
    alert("Accept target cancelled!");
    return false;
    }
}
function wiznav_alertConfirmation(confirmMsg) {
               var retVal = confirm(confirmMsg);
               if( retVal == true ) {
                  return true;
               } else {
                  return false;
               }
}
function wiznav_addmtl(){
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">adding timelines...</h1>").hide().fadeIn(500);
wiz_showloading();
wiz_addmtl();
}
function wiznav_addsmtl(){
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">adding spawn timelines...</h1>").hide().fadeIn(500);
wiz_showloading();
wiz_addsmtl();
}
function wiznav_savespawntasks(){
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">saving table as the template spawn task list...</h1>").hide().fadeIn(500);
wiz_showloading();
alert("DUMMY:"+$('#dummy_input').val());
alert("WIZ_MSG"+$('#wiz_msg').html());
alert("ALWAYS?:"+$('#always_here').val());
console.log("WITHFIND:"+$('#spawn_task_list').find('#task_name_0').val());
console.log("JQUERY .CONTENTS:"+$('#dummy_input',$("#myco_app").contents()).val());
console.log("SAME LEVEL:"+$('#dummy_input').val());
wiz_savespawntasks();
}
function wiznav_savesubstratetasks(){
$('#wiz_msg').html("<h1 class=\"wiz_msg\" id=\"wiz_msg\">saving table as the template substrate task list...</h1>").hide().fadeIn(500);
wiz_showloading();
wiz_savespawntasks();
}
async function wiz_savesubstratetasks(){
}

// I was in the process of figuring out how to serialize the form inputs
function formToJSON( selector )
{
     var form = {};
     $(selector).find(':input[name]:enabled').each( function() {
         var self = $(this);
         var name = self.attr('name');
         if (form[name]) {
            form[name] = form[name] + ',' + self.val();
         }
         else {
            form[name] = self.val();
         }
     });

     return form;
}
function getIndexedArray($thisform){
    var unindexed_array = $thisform.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });
    console.log(indexed_array);
    return indexed_array;
}

// this adds a row of inputs for an inserted task dynamically to our spawn task list form
function addSpawnTaskRow(){
var count = Date.now();
    $('#spawn_task_list').append($('<div>', {name: 'taskdiv_'+count, id: 'taskdiv_'+count}));
    $('#taskdiv_'+count).append("TASK<br>");
    $('#taskdiv_'+count).append($('<input>',{name: 'task_type_'+count, id: 'task_type_'+count,type: 'hidden'}));
    $('#taskdiv_'+count).append($('<input>',{name: 'task_name_'+count, id: 'task_name_'+count,type: 'text'}));
    $('#taskdiv_'+count).append($('<input>',{name: 'task_description_'+count, id: 'task_description_'+count,type: 'text'}));
    $('#taskdiv_'+count).append($('<input>',{name: 'task_order_'+count, id: 'task_order_'+count,type: 'text'}));
            /*
            var task_list_form_append="<div id=\"addedtaskdiv_"+Date.now()+"\" class=\"task_list_item\">";
            task_list_form_append+="TASK<br>";
            task_list_form_append+="<input type=\"hidden\" name=\"task_type[]\" id=\"task_type_"+Date.now()+"\" value=\"spawn\" />";
            task_list_form_append+="<label id=\"addedtaskdiv_"+Date.now()+"\" class=\"task_item_label\">Task Name</label><input class=\"task_input\" id=\"task_name_"+Date.now()+"\" type=\"text\" name=\"task_name[]\" value=\"\" />";
            task_list_form_append+="<label id=\"addedtaskdiv_"+Date.now()+"\" class=\"task_item_label\">Task Description</label><input class=\"task_input\" id=\"task_description_"+Date.now()+"\" type=\"text\" name=\"task_description[]\" value=\"\" />";
            task_list_form_append+="<label id=\"addedtaskdiv_"+Date.now()+"\" class=\"task_item_label\">Task Order</label><input class=\"task_input\" type=\"text\" id=\"task_order_"+Date.now()+"\" name=\"task_order[]\" value=\"\" />";
            task_list_form_append+="</div>";
            $('#spawn_task_list').append(task_list_form_append);
            */
}
async function wiz_savespawntasks(){
// do ajax update using the cloned / edited items
// when we use "#always_there the static form and inputs in our wizard html page we can see the function passes a valid json object via get
// when we use our intended form the object is empty because the element is inaccessible and is 'undefined'
    $.ajax({
           url   : 'tasks?s=ttsave',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data:  {
        task_type : "spawn",    
        task_list : JSON.stringify($('#always_there').serializeArray()),
        gethello : "helloget",
       },
           success: function(response){
        console.log(response);
        if(response.status=="OK"){
        $('#wiz_msg').html(response.wiz_msg);
        // show what it thinks we have
        $('#wiz_main').html(response.task_list);

        }else if(response.status=="ERR"){
        $('#wiz_main').html(response.err_msg);
        }
           },
       error: function(xhr, ajaxOptions, thrownError){
        $('#wiz_main').html(xhr.status + " " +thrownError);
       }
    });
}
async function wiz_getspawntasktemplate(){
// if both selections made ask the backend to try and return the task list template
if(!$('#myco_spawncontainer').val()||!$('#myco_spawnmedia').val()){return false;}
    $.ajax({
           url   : 'tasks?s=ttlist',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data: { 
        "media_container_id" : $('#myco_spawncontainer').val(),
        "media_type_id" : $('#myco_spawnmedia').val(),
        "task_type" : 'spawn',
        },
           success: function(response){
        console.log("getspawntasktemplate : "+response.status);
        if(response.status=="OK"){
        $('#wiz_msg').html(response.wiz_msg);
        if(response.task_list.length){
        var $tasklistform = $('<form />', {name: 'spawn_task_list', id: 'spawn_task_list'});
        $('#spawn_adapttasks_tablediv').append($tasklistform);
        response.task_list.forEach((taskitem,count) => {
            //console.log(count + " " + taskitem.task_name);
            var $taskrowholdingdiv = $('<div />', {name: 'taskdiv_'+count, id: 'taskdiv_'+count});
            var $task_type_el = $('<input />',{name: 'task_type_'+count, id: 'task_type_'+count,type: 'hidden',value: taskitem.task_type});
            var $task_name_el = $('<input />',{name: 'task_name_'+count, id: 'task_name_'+count,type: 'text',value: taskitem.task_name});
            var $task_description_el = $('<input />',{name: 'task_description_'+count, id: 'task_description_'+count,type: 'text',value: taskitem.task_description});
            var $task_order_el = $('<input />',{name: 'task_order_'+count, id: 'task_order_'+count,type: 'text',value: taskitem.task_order});
            $tasklistform.append($taskrowholdingdiv);
            $taskrowholdingdiv.append("TASK<br>");
            $taskrowholdingdiv.append($task_type_el);
            $taskrowholdingdiv.append($task_name_el);
            $taskrowholdingdiv.append($task_description_el);
            $taskrowholdingdiv.append($task_order_el);

            // the original 'stuff in the html' way effort
            /*      
            task_list_inputs+="<div id=\"taskdiv_"+Date.now()+"\" class=\"task_list_item\">";
            task_list_inputs+="TASK<br>";
            task_list_inputs+="<input type=\"hidden\" id=\"task_type_"+count+"\" name=\"task_type[]\" value=\"spawn\" />";
            task_list_inputs+="<label class=\"task_item_label\">Task Name</label><input class=\"task_input\" type=\"text\" id=\"task_name_"+count+"\" name=\"task_name[]\" value=\""+taskitem.task_name+"\" />";
            task_list_inputs+="<label class=\"task_item_label\">Task Description</label><input class=\"task_input\" type=\"text\" id=\"task_description_"+count+"\" name=\"task_description[]\" value=\""+taskitem.task_description+"\" />";
            task_list_inputs+="<label class=\"task_item_label\">Task Order</label><input class=\"task_input\"type=\"text\" id=\"task_order_"+count+"\" name=\"task_order[]\" value=\""+taskitem.task_order+"\" />";
            task_list_inputs+="</div>";
            */
        });
        
        var $task_list_add=$('<button />', {name: 'buttonadd', id: 'spawn_task_list_add_item',text: 'Add Row'});
        $task_list_add.on('click',function(){addSpawnTaskRow();});
        //<button id=\"spawn_task_list_add_item\" value=\"Add row\" name=\"buttonadd\" > Add row</button>";
        //task_list_buttons+="<script>$('#spawn_task_list_add_item').on('click',function(){addSpawnTaskRow();});</script>";
        //$('#spawn_adapttasks_tablediv').html(task_list_form);     
        //$('#spawn_task_list').append(task_list_inputs);
        $('#spawn_adapttasks_tablediv').append($task_list_add);
        // I tried loading the js specific to this wizpage after the fact by loading the below version external to no effect        
        //$('#spawn_adapttasks_tablediv').append("<script type=\"text/javascript\" src=\"wiz_savespawntasks.js\"></script>");
        }else{
        // if theres no task list template being returned clear out the adapttasks_tablediv
        $('#spawn_adapttasks_tablediv').html("");       
        }
        //$('#spawn_adapttasks_tablediv').html(task_list_form);
        wiz_shownav(103);
        }else if(response.status=="ERR"){
        $('#spawn_adapttasks_tablediv').html(response.err_msg);
        }

           },
       error: function(xhr, ajaxOptions, thrownError){
        $('#wiz_main').html(xhr.status + " " +thrownError);
       }
    });

}
async function wiz_getsubstratetasktemplate(){
// will become just gettasktemplate
}

async function wiz_addmtl(){
// adds a media timeline for media/container
// will become just addtl()
    $.ajax({
           url   : 'targets?s=addmtl',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data: { 
        "species" : WIZ['species'],
        "media_container_id" : WIZ['media_container_id'],
        "media_type_id" : WIZ['media_type_id'],
        "days_pin" : WIZ['days_pin'],
        "days_incubate" : WIZ['days_incubate'],
        "days_fruit" : WIZ['days_fruit'],
        },
           success: function(response){
        if(response.status=="OK" && response.last_insert_id){
        wiznav_propose();
        }else if(response.status=="ERR"){
        $('#wiz_main').html(response.err_msg);  
        }
           },
       error: function(){
        $('#wiz_main').html("an error occured fetching our wiz step");
       }
    });
}
async function wiz_addsmtl(){
// adds a spawn media timeline for media/container
// will become just addtl()
    $.ajax({
           url   : 'targets?s=addsmtl',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data: { 
        "species" : WIZ['species'],
        "spawn_media_container_id" : WIZ['spawn_media_container_id'],
        "spawn_media_type_id" : WIZ['spawn_media_type_id'],
        "spawn_days_incubate" : WIZ['spawn_days_incubate'],
        },
           success: function(response){
        if(response.status=="OK" && response.last_insert_id){
        wiznav_propose();
        }else if(response.status=="ERR"){
        $('#wiz_main').html(response.err_msg);  
        }
           },
       error: function(){
        $('#wiz_main').html("an error occured fetching our wiz step");
       }
    });
}

async function wiz_getpropose(){
//console.log("PROPOSE CURRENT SPEC NAME:"+WIZ['species_name']);
    $.ajax({
           url   : 'targets?s=propose',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data: { 
        "target_date" : WIZ['target_date'],
        "species" : WIZ['species'],
        "species_name" : WIZ['species_name'],
        "weightkg" : WIZ['weightkg'],
        "media_container_id" : WIZ['media_container_id'],
        "media_type_id" : WIZ['media_type_id'],
        "media_type_name" : WIZ['media_type_name'],
        "spawn_media_type_name" : WIZ['spawn_media_type_name'],
        "spawn_media_type_id" : WIZ['spawn_media_type_id'],
        "spawn_media_container_id" : WIZ['spawn_media_container_id'],
        "spawn_percent" : WIZ['spawn_percent'],
        "be_percent" : WIZ['be_percent'],

        },
           success: function(response){
        //console.log(response);
        $('#wiz_msg').html(response.wiz_msg);
        if(response.status=="OK"){
        if(response.blocks_required){WIZ['blocks_required']=response.blocks_required;}
        if(response.spawn_media_container_requiredcount){WIZ['spawn_media_container_requiredcount']=response.spawn_media_container_requiredcount;}
        if(response.media_latest_inoculation_date){WIZ['media_latest_inoculation_date']=response.media_latest_inoculation_date;}
        if(response.spawn_media_latest_inoculation_date){WIZ['spawn_media_latest_inoculation_date']=response.spawn_media_latest_inoculation_date;}
        if(response.media_days_of_incubation){WIZ['media_days_of_incubation']=response.media_days_of_incubation;}
        if(response.media_days_of_pinning){WIZ['media_days_of_pinning']=response.media_days_of_pinning;}
        if(response.media_days_of_fruiting){WIZ['media_days_of_fruiting']=response.media_days_of_fruiting;}
        if(response.spawn_media_days_of_incubation){WIZ['spawn_media_days_of_incubation']=response.spawn_media_days_of_incubation;}
        WIZ['media_totalblocksdays']=Number(WIZ['media_days_of_incubation'])+Number(WIZ['media_days_of_fruiting'])+Number(WIZ['media_days_of_pinning']);
        WIZ['target_totaldays']=Number(WIZ['media_totalblocksdays'])+Number(WIZ['spawn_media_days_of_incubation']);
        var proposalout="<p class=\"wiz_summary\">Producing " + 
            WIZ['weightkg'] + " kilograms of " + WIZ['species_name'] + 
            " will require " + WIZ['blocks_required'] + " fruiting containers "+WIZ['media_container_name']+
            " given the provided estimated biological efficiency " + WIZ['be_percent'] +"%,"+
            "<br><br>Innoculation occurs on or before "+WIZ['media_latest_inoculation_date'] +
            " in order to provide time for colonization, pinning, fruiting, and to meet the target delivery date "+WIZ['target_date'] +
            " in time.<br><br>Inoculation of the "+WIZ['blocks_required']+" fruiting media blocks will require " +WIZ['spawn_media_container_requiredcount'] + 
            " " + WIZ['spawn_media_container_name'] +" of "+WIZ['spawn_media_type_name'] + ", inoculated on or before " + WIZ['spawn_media_latest_inoculation_date'] + " "+
            ", with a period of "+WIZ['spawn_media_days_of_incubation']+
            " days for inoculation and colonization of the spawn, and for the subsequent inoculation, incubation, pinning, and fruiting of the substrate blocks, which occurs over a period of "+WIZ['media_totalblocksdays']+" days<br><br>Our production target is cycled 'source' -> 'spawn' -> 'fruited block' overall, and amounts to a period of "+WIZ['target_totaldays']+" days</p><br>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Target Date</div><div class=\"proposalitem_val\">"+WIZ['target_date']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Target Weight</div><div class=\"proposalitem_val\">"+WIZ['weightkg']+"kg</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Target Total Days</div><div class=\"proposalitem_val\">"+WIZ['target_totaldays']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Species</div><div class=\"proposalitem_val\">"+WIZ['species_name']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Fruiting Container</div><div class=\"proposalitem_val\">"+WIZ['media_container_name']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Fruiting Media</div><div class=\"proposalitem_val\">"+WIZ['media_type_name']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Estimated B.E.</div><div class=\"proposalitem_val\">"+WIZ['be_percent']+"%</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Blocks Required</div><div class=\"proposalitem_val\">"+WIZ['blocks_required']+"</div></div>";

        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Blocks Days Incubation</div><div class=\"proposalitem_val\">"+WIZ['media_days_of_incubation']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Blocks Days Pinning</div><div class=\"proposalitem_val\">"+WIZ['media_days_of_pinning']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Blocks Days Fruiting</div><div class=\"proposalitem_val\">"+WIZ['media_days_of_fruiting']+"</div></div>";

        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Blocks Latest Inoculation</div><div class=\"proposalitem_val\">"+WIZ['media_latest_inoculation_date']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Media</div><div class=\"proposalitem_val\">"+WIZ['spawn_media_type_name']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Container</div><div class=\"proposalitem_val\">"+WIZ['spawn_media_container_name']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Containers Required</div><div class=\"proposalitem_val\">"+WIZ['spawn_media_container_requiredcount']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Latest Inoculation</div><div class=\"proposalitem_val\">"+WIZ['spawn_media_latest_inoculation_date']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Days Incubation</div><div class=\"proposalitem_val\">"+WIZ['spawn_media_days_of_incubation']+"</div></div>";
        proposalout+="<div class=\"proposalitem\"><div class=\"proposalitem_item\">Spawn Ratio</div><div class=\"proposalitem_val\">"+WIZ['spawn_percent']+"%</div></div>";
        $('#wiz_main').html(proposalout);
        }else if(response.status=="ERR"){
        $('#wiz_main').html(response.err_msg);
        }else if(response.status=="ERR_MTLMISSING"){
        wiz_showpage(99);
        }else if(response.status=="ERR_SMTLMISSING"){
        wiz_showpage(100);
        }else if(response.status=="ERR_NOSUBSTRATETASKS"){
        wiz_showpage(102);
        }else if(response.status=="ERR_NOSPAWNTASKS"){
        wiz_showpage(101);
        }

           },
       error: function(xhr, ajaxOptions, thrownError){
        $('#wiz_main').html(xhr.status + " an outside error occured fetching this wiz step<br>"+thrownError);
       }
    });
//console.log(WIZ['species']+ " " + WIZ['species_name']);
}

async function wiz_getcontent(thiswizpage){
var thiscontent = null;
    $.ajax({
           url   : 'targets?s=wizform&id='+thiswizpage,
           type  : 'GET',
       dataType: 'json',
       data: { 
        "species" : WIZ['species'],
        "species_name" : WIZ['species_name'],
        "media_container_id" : WIZ['media_container_id'],
        "media_container_name" : WIZ['media_container_name'],
        "spawn_media_container_id" : WIZ['spawn_media_container_id'],
        "spawn_media_type_id" : WIZ['spawn_media_type_id'],
        "media_type_id" : WIZ['media_type_id'],
        "media_type_name" : WIZ['media_type_name'],
        },
           success: function(response){
        console.log("getcontent : "+response.status+" "+response.formhtml);
        $('#wiz_msg').html(response.wiz_msg);
        $('#wiz_main').html(response.formhtml);
           },
       error: function(xhr, ajaxOptions, thrownError){
        $('#wiz_main').html(xhr.status + " " +thrownError);
       }
    });
}
function wiz_accept(){
    $.ajax({
           url   : 'targets?s=accept',
           type  : 'GET',
       dataType: 'json',
       contentType: 'application/json',
       data: { 
        "target_date" : WIZ['target_date'],
        "species" : WIZ['species'],
        "species_name" : WIZ['species_name'],
        "weightkg" : WIZ['weightkg'],
        "blocks_required":WIZ['blocks_required'],
        "spawn_media_container_requiredcount":WIZ['spawn_media_container_requiredcount'],
        "media_container_id" : WIZ['media_container_id'],
        "media_type_id" : WIZ['media_type_id'],
        "media_type_name" : WIZ['media_type_name'],
        "spawn_media_type_name" : WIZ['spawn_media_type_name'],
        "spawn_media_type_id" : WIZ['spawn_media_type_id'],
        "spawn_media_container_id" : WIZ['spawn_media_container_id'],
        "spawn_percent" : WIZ['spawn_percent'],
        "be_percent" : WIZ['be_percent'],
        "media_days_of_incubation":WIZ['media_days_of_incubation'],
        "media_days_of_pinning":WIZ['media_days_of_pinning'],
        "media_days_of_fruiting":WIZ['media_days_of_fruiting'],
        "spawn_media_days_of_incubation":WIZ['spawn_media_days_of_incubation'],
        "media_totalblocksdays":WIZ['media_totalblocksdays'],
        "target_totaldays":WIZ['target_totaldays'],
        "media_latest_inoculation_date":WIZ['media_latest_inoculation_date'],
        "spawn_media_latest_inoculation_date":WIZ['spawn_media_latest_inoculation_date'],
        },
           success: function(response){
        //console.log(response);
        $('#wiz_msg').html(response.wiz_msg);
        if(response.status=="OK"){
        $('#wiz_main').html("Target inserted: last_id: <a href=\"targets?s=id&id="+response.last_id+"\">"+response.last_id+"</a>");
        }else if(response.status=="ERR"){
        $('#wiz_main').html(response.err_msg);
        }

           },
       error: function(xhr, ajaxOptions, thrownError){
        $('#wiz_main').html(xhr.status + " " +thrownError);
       }
    });

}

So everything works up until wiznav_savespawntasks or wiz_savespawntasks tries to use any of the dynamic elements

If I type in my browser console with the page in question being visible

console.log($('#task_name_0').val());

Then it returns the value, but a script running doing the same thing it's undefined. What do I need to do to have my new elements be available?

  • 1
    Hi, welcome to SO. Please do take the time to read the [tour]. For future reference, please also read [mcve] - with emphasis on *minimal* amount of code to reproduce the issue - there's a lot of code here and there's probably only a couple of lines that are relevant. – freedomn-m Jun 23 '21 at 15:23
  • From the sound of it you need to use a delegated event handler. I'm not sure which parts of your code are relevant to the problem in order to verify my assumption, so I'll just leave you with this link: https://stackoverflow.com/q/203198/519413 – Rory McCrossan Jun 23 '21 at 15:28
  • What you've described would normally occur if your code is running before your ajax (and subsequent html build) has completed, *or* if your selector is not correct. You have `$("#task_name_0")` in your console, but you have `$('#spawn_task_list').find('#task_name_0')` in your code (where I could find the use of task_name_0, maybe there's others elsewhere). So it could be (*will* be) that task_name_0 is not a child of spawn_task_list at the time the code runs. – freedomn-m Jun 23 '21 at 15:29
  • I'm going to work on adjusting my code portions so that the related code is added after other elements are added – Ryan Barrett Jun 23 '21 at 15:34
  • I'm sorry my code isn't runnable on it's own - it's really intertwined with my other aspects of the project... – Ryan Barrett Jun 23 '21 at 15:35
  • What I'm intending to have is a form with a bunch of rows of divs and inside those have a few inputs that have their values set to the results from the json task_list object returned. I'd like to at a minimum add and remove rows from that dynamic table, and then on "save" take those rows, hopefully as an indexed array with named values and pass them back (like the script is already doing with static form elements) to the back end – Ryan Barrett Jun 23 '21 at 15:40
  • I guess also the point about "finding a child" in my case the injected inputs are inside a div container then inside the form. I don't really want to have to "find" anything, I'd like to understand ultimately why my script loaded with the page subsequently doesn't access new elements I can see, that the console see's, but that the script cant see. I'm not sure I understand why the script that created the dynamic element cant then read it's value... – Ryan Barrett Jun 23 '21 at 15:53
  • just to be clear the id '#task_name_0' is part of the generated code, the 0 is the count of the array index of the returned results. you wont find it "in the code" because it's being created on the fly. When I referenced trying to "find" it, I reference it knowing that it "exists" because there were x number of tasks returned in the json object array task_list. anyways I am beyond stumped why the javascript cant access these new elements – Ryan Barrett Jun 23 '21 at 16:40
  • javascript is broken. With regard to 'event delegation' I'm not looking to service a 'change'/'click' or act on 'focus' I just wanna read the current value of the input field - seems pretty straight forward – Ryan Barrett Jun 23 '21 at 18:29

0 Answers0