0

Hi so I'm dynamically creating a checkbox list with children using JavaScript in the Body of the html page, that runs in electron.

But my jQuery code that checks the parent tree items that I got from here works fine only when I add the debugger; after the $(window).on('load', function (e) { line

jQuery code:

<script>

$(window).on('load', function (e) {
    $('input[type=checkbox]').click(function(){
        if(this.checked){
            $(this).parents('li').children('input[type=checkbox]').prop('checked',true);
        }    
        $(this).parent().find('input[type=checkbox]').prop('checked',this.checked); 
    });
});
</script>

example Javascript code to create the list:

            document.getElementById('list').innerHTML='<ul id="file" class="tree"></ul>';
        scan.filesscan('tests', files => {
               files.forEach(function(file, j) {
                   suites = pr.parseFile('tests',file, suite =>{
                       document.getElementById('file').innerHTML+='<li><input type="checkbox" id="' + j +'" name="files" value="' + file + '">' + file + '<ul id="'+file+'" class="tree"></ul></li>';
                       document.getElementById(file).innerHTML+='<li><input type="checkbox" id="' + j + '" name="suite" value="' + suite.name + '">' + suite.name + '<ul id="'+suite.name+'"></ul></li>';
                       for (let i = 0; i < suite.tests.length; i++) {
                           document.getElementById(suite.name).innerHTML+='<li><input type="checkbox" id="' + j + '" name="'+suite.name+'" value="' + suite.tests[i] + '">' + suite.tests[i] + '</li>';                           
                        }
                   });  
                });
        });

As stated the code works fine but only when I have the debugger; line in after window.on load this is obviously a timing issue how would I resolve this?

Miellies
  • 13
  • 5
  • You need to use a delegated event handler as you're creating the elements after the DOM loads. See the duplicate I marked for more informaion. `window.onload` is guaranteed to be a fix for this timing issue. I'd suggest using `$(document).ready(fn)` instead, assuming you aren't specifically waiting for images to load in the DOM. – Rory McCrossan Apr 05 '18 at 10:11
  • @RoryMcCrossan I've used both the window.onload and document.ready and having the same issue in both iterations. I took a look at your example on event binding how would I rewrite the event listener to find when the asynchronous Node.js scan.filescan/files.for each function to end. – Miellies Apr 05 '18 at 10:54
  • `$('#list').on('change', 'input[type=checkbox]', function() ...` – Rory McCrossan Apr 05 '18 at 10:55
  • Thanks seems to be working now but only after the second click of a checkbox. – Miellies Apr 05 '18 at 11:05
  • @RoryMcCrossan is there any reason why this script only selects everything after the second click? – Miellies Apr 05 '18 at 11:44

0 Answers0