Liondancer
Liondancer

Reputation: 16469

Testing jQuery/JS output on Chrome developer tools

I have a method that creates 2 arrays with data. I want to be able to include these arrays into JSON. Here is my code:

$(document).ready(function() {
    $("button").click(function(){
        var configs = [];
        var testPages = [];
        $(".test input:checked").each(function() {
            testPages.push($(this).attr('id'));
        });
        $(".config input:checked").each(function() {
            configs.push($(this).attr('id'));
        });
        //console.log(configs);
        //console.log(testPages);

        var testJson = new Object();
        testJson.testpages = testPages;
        testJson.configurations = configs;
        var runTestJson = JSON.stringify(testJson);
        return runTestJson;
    });
});

I want to be able to test this against my page but I am new to jQuery, Javascript and also using Chrome developer tools. I'm not sure how to test this in the Chrome console.

The commented portion (console.log()s) were displayed but when I type configs or testPages to try to view the array, I would get the error that they were undefined. How do I test to see if I am getting the correct output for my code on Chrome developer tools?

Upvotes: 0

Views: 2001

Answers (2)

T J
T J

Reputation: 43156

You can debug your JavaScript without populating global space as follows (Instruction based on chrome, but similar in major browsers):

  • Open developer console F12
  • go to Sources tab
  • Open your script file (Ctrl + o and type the filename)
  • Put a breakpoint by clicking on the line number you wish to debug
  • Refresh your page an execution will be stopped at that line

. You can further use the available controls in the debug toolbar: enter image description here

to proceed the execution as you wish, each controls have self-descriptive tooltips. You can see the values in variables by hovering over them or manually selecting them.

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

You'd need to make those two variables global. Just beware that unnecessarily polluting the global scope is not recommended. But if it's just for testing, then i suppose it's OK.

// global scope
var configs = [];
var testPages = [];
$(document).ready(function() {
    $("button").click(function(){
        $(".test input:checked").each(function() {
            testPages.push($(this).attr('id'));
        });
        $(".config input:checked").each(function() {
            configs.push($(this).attr('id'));
        });
        //console.log(configs);
        //console.log(testPages);

        var testJson = new Object();
        testJson.testpages = testPages;
        testJson.configurations = configs;
        var runTestJson = JSON.stringify(testJson);
        return runTestJson;
    });
});

Upvotes: 2

Related Questions