简体   繁体   中英

Use value of select option as name for a variable in Javascript

I have a select form with different options. I want to get the value of the option that is selected when it changes. The value has the same name of a variable that put in a function.

So i want to put the value of the selected option into my function as a variable. How should i do this?

this is my select form

<select class="select">
      <option  value="value1" >option 1</option>
      <option  value="value2" >option 2</option>
      <option  value="value3" >option 3</option>
</select>

this is my javascript

var value1 = ['item1', 'item2', "item3", ...]

$(".select").change(function (){
    $(".select option:selected").each(function(){

          var dataset = $(this).val();          

              d3.select(".chart")
               .selectAll("div")
               .data(dataset)
               .enter();
    });
});

Instead of flooding your global scope, use an object to hold the possible combinations. reference the object with the value.

var dataPoints = {
    value1 : ['item1', 'item2', "item3", ...],
    value2 : ['item1', 'item2', "item3", ...]
};

$(".select").change(function (){
    $(".select option:selected").each(function(){

          var dataset = $(this).val();          

              d3.select(".chart")
               .selectAll("div")
               .data(dataPoints[dataset])
               .enter();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM