title: Chart not rendering w/Chart.js on button click
body: <p>I have a web app that presents a form to users for drawing a chart w/ Chart.js. </p>
  
  <p>I collect the form data on button click, format it correctly and then want to render the chart. </p>
  
  <p>Here is the code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// /public/main.js
  const chartData = {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 16, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ]
    }]
  };
  const barOptions = {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  };
  
  const ctx = document.getElementById("myChart").getContext('2d');
  
  const myChart = new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: barOptions
  });
  // Get Chart Info from form
  
  $(document).ready(function() {
    $("#render_btn").on("click", function(e) {
      e.preventDefault();
  
      // First grab form data off the page
      const formData = $("form").serializeArray();
      // Get Chart Type Seperate from Form Data
      const chartType = document.getElementById('chart_type').value;
  
      // Create a data Object for Chart constructor to use
      const chartData = {
        datasets: []
      };
      let datasetsItem = {};
  
      // Convert formData array to chartData object
      formData.forEach(function(value, index) {
        if (formData[index].name == 'labels') {
          chartData[(formData[index].name)] = formData[index].value;
        } else {
          datasetsItem[formData[index].name] = formData[index].value;
          chartData.datasets[0] = datasetsItem;
        }
      });
  
      // Now we have to do some converting i.e., chartData.labels must be
      // converted to array from string etc
      chartData.datasets[0].backgroundColor = splitString(chartData.datasets[0].backgroundColor);
      chartData.datasets[0].data = strToNumberArray(chartData.datasets[0].data);
      chartData.labels = splitString(chartData.labels);
  
      // Check if succesful
      try {
        if (!(chartData.datasets[0].backgroundColor) || !(chartData.datasets[0].data) || !(chartData.labels)) {
          throw new Error("Input Error. Recheck your form data.");
        }
  
        myChart.update({
          type: chartType,
          data: chartData
  
        });
      } catch (error) {
        alert(error);
      }
  
  
      // ============================================================= //
      // ============= Function definitions ========================== //
      // ============================================================= //
      function splitString(strToSplit, separator = ',') {
        if (strToSplit === undefined) {
          console.log("Error: splitString is empty.");
          return "";
        }
  
        // Test for a comma in the string
        const result = /,+/.test(strToSplit);
        if (!result) {
          alert(`Comma delimiter missing from ${strToSplit}`);
          return false;
        }
  
        // Split a string into an array and trim any whitespace
        let arrayOfStrings = strToSplit.split(separator);
        arrayOfStrings.forEach(function(value, index) {
          arrayOfStrings[index] = value.trim();
        });
  
        return arrayOfStrings;
      }
  
      // Function to convert string to an array then convert each element to a number
      function strToNumberArray(str, separator = ',') {
        if (str === undefined) {
          alert('Error: string is empty.');
          return "";
        }
        // Test for a comma in the string
        const result = /,+/.test(str);
        if (!result) {
          alert(`Comma delimiter missing from ${str}`);
          return false;
        }
  
        let arrayOfNumbers = str.split(separator).map(Number);
  
        return arrayOfNumbers;
      }
  
      // ============================================================== //
      // ================== End Function Definitions ================== //
      // ============================================================== //
    }); // .on "click"
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"&gt;&lt;/script&gt;
  
  &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;&lt;/script&gt;
  
  &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"&gt;&lt;/script&gt;
  
  &lt;canvas id="myChart" width="400" height="400"&gt;&lt;/canvas&gt;
  
  &lt;h2&gt;Input your values:&lt;/h2&gt;
  &lt;!-- Chart Input Form --&gt;
  &lt;!-- We dont want chart_type as part of form when we use serializeArray
          gather the data and use in chartData object --&gt;
  &lt;div class="row"&gt;
    &lt;div class="col-md-4 col-md-offset-4"&gt;
      &lt;div class="form-group"&gt;
        &lt;label for="chart_type"&gt;Chart Type&lt;/label&gt;
        &lt;input type="text" name="type" class="form-control" id="chart_type" placeholder="Chart Type"&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;form&gt;
    &lt;div class="row"&gt;
      &lt;div class="col-md-4 col-md-offset-4"&gt;
        &lt;div class="form-group"&gt;
          &lt;label for="chart_Label"&gt;Chart Label&lt;/label&gt;
          &lt;input type="text" name="label" class="form-control" id="chart_Label" placeholder="Chart Label"&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
    &lt;div class="row"&gt;
      &lt;div class="col-md-6 col-md-offset-4"&gt;
        &lt;div class="form-group"&gt;
          &lt;label for="chart_labels"&gt;Chart Labels&lt;/label&gt;
          &lt;input type="text" name="labels" class="form-control" id="chart_labels" placeholder="Apr, May, June Note:Seperated by Commas"&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
    &lt;div class="row"&gt;
      &lt;div class="col-md-6 col-md-offset-4"&gt;
        &lt;div class="form-group"&gt;
          &lt;label for="chart_data"&gt;Chart Data&lt;/label&gt;
          &lt;input type="text" name="data" class="form-control" id="chart_data" placeholder="i.e., 25 44 60 etc"&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  
    &lt;div class="row"&gt;
      &lt;div class="col-md-6 col-md-offset-4"&gt;
        &lt;div class="form-group"&gt;
          &lt;label for="chart_colors"&gt;Chart Colors&lt;/label&gt;
          &lt;input type="text" name="backgroundColor" class="form-control" id="chart_colors" placeholder="i.e., red, blue, yellow, purple"&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="row"&gt;
      &lt;div class="col-md-4 col-md-offset-5"&gt;
        &lt;button class="btn btn-primary btn-lg" id="render_btn"&gt;Render Graph&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/form&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>When I click button I get nothing. </p>
  
  <p>If I populate the chart data object w/some data and declare a new <code>myChart</code> globally then on page load the chart renders OK but any new data I add and then click form button renders momentarily and then disappears (!?)</p>
  
  <p>Ideally, I would like a blank canvas, have user enter data and then click render button and have chart. I've looked online but nothing involving a form and event handler I could find. </p>
  
  <p>I went over the Chart.js documentation and tried using their examples to no avail w/update and render. </p>
  
  <p>Any help much appreciated...</p>
  
  <p>Update: OK snippet is running with the problem I am having. When you fill in form and click render I get nothing. Thanks I never used snippet. Can anybody use it? 
  P.S. - I added e.preventDefault to snippet thinking maybe default action was intefering w/Chart.js. No good. Also all values should be comma delimited.</p>