atifaltaf atifaltaf - 6 months ago 26
jQuery Question

Print a js variable inside the function

I want to get the value onclick and print it in symbol

"symbol": +sym+
,
.
check my code:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

</head>
<body>
<p>click here</p>

<!-- TradingView Widget BEGIN -->
<script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
var sym = $(this).val();
alert("alert is working but value is not updating in symbol input");
});
});

new TradingView.widget({
"width": 400,
"height": 450,
"symbol": +sym+,
"interval": "D",
"timezone": "Etc/UTC",
"theme": "White",
"style": "1",
"locale": "en",
"toolbar_bg": "#f1f3f6",
"allow_symbol_change": true,
"hideideas": true,
"show_popup_button": true,
"popup_width": "1000",
"popup_height": "650",
"no_referral_id": true
});
</script>
<!-- TradingView Widget END -->


</body>
</html>

Answer

First of all you need to change this "symbol": +sym+, to this: "symbol": sym,. If what you want to achieve is to change the value of the variable "sym" inside the new "TreadingView.widget" object everytime you click on the paragraph "p" you are doing it wrong. You need to update that value everytime the element is clicked, otherwise the widget object will always hold the original value of the variable "sym", you need to 1)Update the "sym" value and then 2)Recreate the widget or update, you may use:

    <!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

</head>
<body>
<p>click here</p>

  <!-- TradingView Widget BEGIN -->
  <script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script>
  <script type="text/javascript">
$(document).ready(function(){    
      $("p").click(function(){
          var sym = $(this).text();
          new TradingView.widget({
              "width": 400,
              "height": 450,
              "symbol": sym,
              "interval": "D",
              "timezone": "Etc/UTC",
              "theme": "White",
              "style": "1",
              "locale": "en",
              "toolbar_bg": "#f1f3f6",
              "allow_symbol_change": true,
              "hideideas": true,
              "show_popup_button": true,
              "popup_width": "1000",
              "popup_height": "650",
              "no_referral_id": true
           });
          alert("alert is working but value is not updating in symbol input");
      });
  });

  </script>
  <!-- TradingView Widget END -->


</body>
</html>