Search code examples
jqueryasp.netasp.net-mvcvisual-studio-2013bootcamp

Accessing a variable that's outside of a script


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>

Solution

  • 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.