Accessing a variable that's outside of a script

1000 Views Asked by At

I have the following code but can't access 'myVariable' from within the script -- I assume because it's a function and 'myVariable' needs to be a global variable. How does one create a global variable?

(Note: this is a .cshtml file in a ASP.NET MVC project in Visual Studio)

<!DOCTYPE html>
<html>
<head>
</head>
<body>

    @{var myVariable = "this is what I want to access and change later in the script";}

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
  ...
        </div>
    </div>
</div>

<script>
    $('[name="optradio1"]').on('change', function () {
        $('#accordion-second').slideToggle();
        $('#accordion-first').slideToggle();
        alert(myVariable);
    })
</script>
</body>
</html>
2

There are 2 best solutions below

2
On BEST ANSWER

You can use data-attributes:

<script id="myScript" data-myvar="@myVariable">
    $('[name="optradio1"]').on('change', function () {
        $('#accordion-second').slideToggle();
        $('#accordion-first').slideToggle();
        alert($('#myScript').data('myvar'));
    });
</script>

Usually put on the HTML content tags because you normally have some unique identifier already or class, but you can do it on script tags as well.

3
On

Please change which is as alert(myVariable);

instead of using that please use the below code.

       var val = parseInt('@myVariable') + 5;
        alert(val);

Try this one.