Cant add the value on select tag using onclick function to google chart datatable

124 views Asked by At

select tag

I've got the function select_value()

<select id="data" onChange="select_value()">
  <option value="['car', 7],['jeep', 2],['taxi', 1]">aaa</option>     
  <option value="['car', 9],['taxi', 1]">bbb</option>   
</select>

I can't call the select_value() function inside google chart...

my script

function select_value() {
  var stringPie = document.getElementById('data').value;
}

google chart

var data = new google.visualization.DataTable();
data.addColumn('string', 'Cartype');
data.addColumn('number', 'Amount');

var stringPie = document.getElementById('data').value; // <==
var arrPie = eval("[" + stringPie + "]");
data.addRows(arrPie);

the chart always stuck on the first option value of select tag...

1

There are 1 answers

0
RobG On

The select element contains values like:

"['car', 7],['jeep', 2],['taxi', 1]"

that appear to be data for multiple rows. You are converting it to an array using eval, which is a very poor strategy.

To avoid eval, convert the string to an appropriate structure using split or JSON.parse, e.g.

Markup:

<select id="data" onChange="select_value(this)">
  <option value="['car', 7],['jeep', 2],['taxi', 1]">aaa</option>     
  <option value="['car', 9],['taxi', 1]">bbb</option>   
</select>

Script:

// Passing this from the listener gives direct access to the
// element on which the event was triggered
function select_value(element) {

  // JSON can't contain single quotes, so replace them with double
  var stringPie = element.value.replace(/'/g,'"');

  // Convert the values to an array of arrays:
  var arrPie = JSON.parse('[' + stringPie + ']');

  // Add the rows only if there are values to add:
  if (arrPie.length) {
    data.addRows(arrPie);
  }
}

JSON.parse is handy because like eval, you can easily specify different types (e.g. string, number) but avoid many of the pitfalls of eval.

Untested, but should work.