LiveEn
LiveEn

Reputation: 3253

add value to existing javascript code on change event

i have a javascript widget that will display a data chart.. and i have an dropdown box which gives the user the ability to change the theme. so when the user selects a theme it should change and show the user the new theme.

Widget code:

<script type="text/javascript">
new TradingView.widget({
  "width": 500,
  "height": 400,
  "interval": "1",
  "timezone": "Etc/UTC",
  "theme": "White",
  "style": "2",

}); 
</script>

HTML/JS code

<select>
    <option value="moonlight">Moon</option>
    <option value="darkness">Dark</option>
</select>

<script>
$(document).on('change','.theme',function(){
      alert(this.value);
    });
</script>

How do i get add the this.value to the widget JS code theme parameter?

Upvotes: 0

Views: 310

Answers (2)

Suhail Keyjani
Suhail Keyjani

Reputation: 488

you can use global variable

var chartParams={
  "width": 500,
  "height": 400,
  "interval": "1",
  "timezone": "Etc/UTC",
  "theme": "White",
  "style": "2",

}
new TradingView.widget(chartParams);
$(document).on('change','.theme',function(){
     chartParams["theme"]=this.value
     new TradingView.widget(chartParams);
    });

Upvotes: 0

Jai
Jai

Reputation: 74738

I guess you should put the new widget code in a function and access the theme from the args:

<script type="text/javascript">
function themeChanger(theme){
  var themeWidget = new TradingView.widget({
    "width": 500,
    "height": 400,
    "interval": "1",
    "timezone": "Etc/UTC",
    "theme": theme,
    "style": "2",

  }); 
  return themeWidget;
}

$(document).on('change','.theme',function(){
   var widget = themeChanger(this.value);
   // do something with widget.
});

</script>

Upvotes: 3

Related Questions