Question

In: Computer Science

Troubleshoot the code to create a dynamic input field to take numerical inputs and label strings...

Troubleshoot the code to create a dynamic input field to take numerical inputs and label strings to draw a pie chart.

<html>

<head>

<title>AddingRows</title>

</head>

<header>

    <h1>AddingRows</h1>

</header>

<style>

table, td {

    border-style:double;

    border-color: black;

}

</style>

<body>

    <table id="shtol">

        <tr>

          <td>Label 2 </td>  

          <td><input type="text" class = "labelIn"/></td>

          <td>Percentage</td>

          <td><input type="number" class = "percentIn"/></td>

        </tr>

        <tr>

            <td>Label 1 </td>  

            <td><input type="text" class = "labelIn"/></td>

            <td>Percentage</td>

            <td><input type="number" class = "percentIn"/></td>

        </tr>

      </table>

      <br>

      <button type="button" onclick="addR()">Add Label</button>

      <button type="button" onclick="drawChart()">Draw the Pie Chart</button>

      <div id="chart_div"></div>

      <p id = "counters" style = "display:none">2</p>

<script>

function addR() {

    var counterHT = document.getElementById('counters');

    var counter = counterHT.innerHTML;

    counter++;

    counterHT.innerHTML = counter;

  var table = document.getElementById("shtol");

  var row = table.insertRow(0);

  var cell1 = row.insertCell(0);

  var cell2 = row.insertCell(1);

  var cell3 = row.insertCell(2);

  var cell4 = row.insertCell(3);

  cell1.innerHTML= "Label " + counter;

  cell2.innerHTML = "<input type = text>";

  cell2.classList.toggle("labelIn");

  cell3.innerHTML = "Percentage ";

  cell4.innerHTML = "<input type = text>";

  cell4.classList.toggle("percentIn");

}

function drawChart(){

    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Label');

    data.addColumn('number', 'Percentage');

    var x = document.getElementsByClassName("labelIn");

    var y = document.getElementsByClassName("percentIn");

    var i;

    for(i = 0; i < x.length; i ++){

        data.addRows([

        [x[1].value,y[1].value]

        ])

    }

    var myTitle = document.getElementById("title").value;

    // Set chart options

    var options = {'title':myTitle,

                    'width':400,

                    'height':300};

    // Instantiate and draw our chart, passing in some options.

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

    chart.draw(data, options);

}

    </script>

</body>

  

</html>

Solutions

Expert Solution

Troubleshooting of the above code  

Creating a dynamic input field to take numerical inputs and label strings to draw a pie chart.

First before going onto the solution of the above code, we have to understand the faults due to which we face problems in our code :

1. Attaching the Google Charts AJAX API : Our code is for creating the Pie Chart by using the Google Charts but we haven't added the AJAX API for Google Charts to load.

In this process we have to load the AJAX API by using following command available on the official Google Charts website:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

2. Loading the Visulaization API and Corechart Package and set a Callback to run when API loaded : This step is added to our code as it is necessary to load all the Core Charts and the API for visualizing those charts in our code. And We also have to set a callback to run when the API is loaded and a function for displaying charts is called to show the chart in our browser.

We can load these by using the following Commands:

<!-- Load the Visualization API and corechart -->
google.charts.load('current', {'packages':['corechart']});

<!-- Setting a callback to run -->
google.charts.setOnLoadCallback(drawChart); 

3. Adding the "class" with the inputs taken by dynamically extended Row elements : In the addR() function we used the toggle function to add the class name with the extanded row elements which returns the value NaN for the elements.

Wrong Code part:

cell1.innerHTML= "Label " + counter;

cell2.innerHTML = "<input type = text>";

cell2.classList.toggle("labelIn");

cell3.innerHTML = "Percentage ";

cell4.innerHTML = "<input type = text>";

cell4.classList.toggle("percentIn");

Hence Instead of using toggle we directly provide the class names to the input values to bind them with the respective classes.
Correct Code Part :

    cell1.innerHTML= "Label " + counter;
 
    cell2.innerHTML = '<input type = "text" class = "labelIn"/>';

    cell3.innerHTML = "Percentage ";

    cell4.innerHTML = '<input type = "number" class = "percentIn"/>';

4. We have to provide the Title field to input the title because we can't leave title field empty.

<label>Enter title for the Pie Chart</label>
    <input type="text" id = "title"/>

5. In drawChart() function in the loop we have to take the all object values to pass the values in the Chart so instead of using the 1 we use i to extract the values in [x[i].value,parseInt(y[i].value)] and for the yth value we must have to convert it into integer.

Hence we use parseInt() function to convert it into integer.

for(i = 0; i < x.length; i ++){

        data.addRows([

        [x[i].value,parseInt(y[i].value)]

        ])

    }

Hence by correcting all the above mistakes we come to our final code.

Here is the troubleshooted final code with all corrections that will give the correct required output :

<html>

<head>

<title>AddingRows</title>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>


<script type="text/javascript">

  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart); 



  function addR() {

    var counterHT = document.getElementById('counters');

    var counter = counterHT.innerHTML;

    counter++;

    counterHT.innerHTML = counter;

    var table = document.getElementById("shtol");

    var row = table.insertRow(0);

    var cell1 = row.insertCell(0);

    var cell2 = row.insertCell(1);

    var cell3 = row.insertCell(2);

    var cell4 = row.insertCell(3);

    cell1.innerHTML= "Label " + counter;
 
    cell2.innerHTML = '<input type = "text" class = "labelIn"/>';

    cell3.innerHTML = "Percentage ";

    cell4.innerHTML = '<input type = "number" class = "percentIn"/>';

  }

  function drawChart(){

    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Label');

    data.addColumn('number', 'Percentage');

    var x = document.getElementsByClassName("labelIn");

    var y = document.getElementsByClassName("percentIn");

    var i;

    for(i = 0; i < x.length; i ++){

        data.addRows([

        [x[i].value,parseInt(y[i].value)]

        ])

    }

    var myTitle = document.getElementById("title").value;

    // Set chart options

    var options = {'title':myTitle,

                    'width':400,

                    'height':300};

    // Instantiate and draw our chart, passing in some options.

    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

    chart.draw(data, options);

  }

</script>

</head>

<header>

    <h1>AddingRows</h1>

</header>

<style>

table, td {

    border-style:double;

    border-color: black;

}

</style>

<body>
    <label>Enter title for the Pie Chart</label>
    <input type="text" id = "title"/>

    <table id="shtol">

        <tr>

          <td>Label 2 </td>  

          <td><input type="text" class = "labelIn"/></td>

          <td>Percentage</td>

          <td><input type="number" class = "percentIn"/></td>

        </tr>

        <tr>

            <td>Label 1 </td>  

            <td><input type="text" class = "labelIn"/></td>

            <td>Percentage</td>

            <td><input type="number" class = "percentIn"/></td>

        </tr>

      </table>

      <br>

      <button type="button" onclick="addR()">Add Label</button>

      <button type="button" onclick="drawChart()">Draw the Pie Chart</button>

      <div id="chart_div"></div>

      <p id = "counters" style = "display:none">2</p>

</body>

  

</html>

The screenshot of output of the above code is attached below :


Related Solutions

Take the following code and modify the if(args >= 3) statement to work with a dynamic...
Take the following code and modify the if(args >= 3) statement to work with a dynamic amount of inputs. Example: ./cat file1 file2 file3 file4 filen-1 filen should output a text file that concatenates the files file1 to filen into one file #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) {    char ch;    if (argc ==1)    {        while((ch = fgetc(stdin)) != EOF) fputc(ch, stdout);    }    if (argc == 2)    {   ...
In this homework, we will write the code that will take an expression (input) from the...
In this homework, we will write the code that will take an expression (input) from the user in infix notation and convert that to corresponding postfix notation and evaluate its value. Task 0: Use the starter code to start. All the needed functions and their functionalities are given in the starter code. Task 1: Complete the startercodeinfixtopostfix.c file Task 2: Complete the startercodeevaluatepostfix.c file Sample Input/Output: (Infix to postfix) Input: (A + B)*C-D*E Output: A B + C * D...
Answer in Python: show all code 3) Modify your code to take as input from the...
Answer in Python: show all code 3) Modify your code to take as input from the user the starting balance, the starting and ending interest rates, and the number of years the money is in the account. In addition, change your code (from problem 2) so that the program only prints out the balance at the end of the last year the money is in the account. (That is, don’t print out the balance during the intervening years.) Sample Interaction:...
C++, Need to create a code that will calculated the statistics for character input? This is...
C++, Need to create a code that will calculated the statistics for character input? This is the prompt for the code. I truly understand nothing of what it's asking. Ask the user for one character (terminated by a carriage return).Using flow control, classify the character into one of these categories: 1)           vowel 2)           consonant 3)           digit (0-9) 4)           other Output the character input, its numeric decimal value, and the classification. Total up the number of each type of character entered....
4 Bit Controlled Comparator SPECIFICATIONS: INPUTS:
Create a circuit in Logisim that will take the following...
4 Bit Controlled Comparator SPECIFICATIONS: INPUTS:
Create a circuit in Logisim that will take the following inputs: A : 4 bit binary number B : 4 bit binary number C : Control where: if C = 0, A and B will be treated as unsigned binary if C = 1, A and B will be treated as 2’s complement signed binary (for example, the number 101 represents the value ‘5’ if it is treated as unsigned binary, but it represents...
Utilizing PHP and HTML code Create a form that has text inputs for two numbers and...
Utilizing PHP and HTML code Create a form that has text inputs for two numbers and a submit button. Submit the values to a program that calculates and displays the GCD of the two numbers. The greatest common divisor of two integers a and b is the largest integer that is a factor of both a and b. The GCD of any number and 1 is 1, and the GCD of any number and 0 is that number. For example:...
Using what you know about how to take inputs and make outputs to the console, create...
Using what you know about how to take inputs and make outputs to the console, create a check printing application. Your application will read in from the user an employee's name and salary, and print out a Console Check similar to the following. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > | $1,000,000 | > > > > ___Pay to the Order of___ Johnny PayCheck > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Please only use technique from chapter 1 through 3 in C++ from control structure through object 9th edition
Your are to take the following c code and do the following on Eve: create a...
Your are to take the following c code and do the following on Eve: create a file with the code called quiz32.c create a second file with the code called quiz64.c Using gcc and stopping it after the Assembly phase, generate an optimization level 1, 32 bit ISA relocatable object file for quiz32.c Using gcc and stopping it after the Assembly phase, generate an optimization level 1, 64 bit ISA relocatable object file for quiz64.c obtain a list of the...
Matlab Code that does the following: Takes as input 3 frequencies. Create a signal that is...
Matlab Code that does the following: Takes as input 3 frequencies. Create a signal that is a mixture of the 3 signals. Create a bandpass filter that only selects the center frequency. Output the filtered signal which contains only the middle frequency. Plot in time and frequency domain the original signal and the filtered signal. Show the output for filter order 1 and 15. Upload a pdf of the image files. Each figure should have your name in the title...
Write code in C please. #1 Write a function multiples() which will take an integer input...
Write code in C please. #1 Write a function multiples() which will take an integer input and it will print out all the multiples of this number starting from 2 but not including itself. For example, multiples(10) will print 2, 5 and multiples(100) will print 2, 4, 5, 10, 20, 25, 50 #2 Write and test a Fibonacci() function that uses a loop instead of recursion to calculate Fibonacci numbers.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT