1

I want to set a cookie value when user clicks on a link. I am using the following code:

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="../../Scripts/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {

        function changeLang(lang) {
            $.cookie('myCulture', lang);
            window.location.reload();
            return false;
        }
    });

</script>

HTML

  <a href="#" onclick="changeLang('da-DK')"><img src="../../Content/images/danishFlag.png" height="35px" width="35px"/></a>

  <a href="#" onclick="changeLang('sv-SE')"><img src="../../Content/images/swedishFlag.png" height="35px" width="35px"/></a>

It looks like very simple code, but when I click on the link, there is an error in the browser. It says.

ReferenceError: changeLang is not defined   

changeLang("da-DK");

Where am I doing wrong??

1
  • relocate your function to out of document ready Commented Dec 6, 2012 at 10:31

5 Answers 5

2

you are defining the function inside the document ready scope, so it's not global therefore not available in the global scope

define it as a global simply by removing the var declaration or using window.changeLang = function

 $(document).ready(function () {

       changeLang = function(lang) {
            document.cookie = 'myCulture' + lang;
            window.location.reload();
            return false;
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

2

define function outside of the jquery block

$(document).ready(function () {
});

function changeLang(lang) {
        $.cookie('myCulture', lang);
        window.location.reload();
        return false;
    }

2 Comments

TypeError: $.cookie is not a function
yes i have the file. i took it from here: github.com/carhartl/jquery-cookie
0

Try moving the ChangeLang function to outside of the Document Ready section. Also, if running in FireFox with Firebug you can experiment with executing the function directly from the Console.

Good luck

Comments

0

Please do not attach js functions in html like this. You're using jquery so just do this:

$(document).ready(function () {

    function changeLang() {
        $.cookie('myCulture', $(this).data('lang'));
        window.location.reload();
        return false;
    }
    $('.link').on('click', changeLang);
});

and then in html:

<a href="#" data-lang="da-DK">...</a>

Comments

0
$(document).ready(function () {
});
function changeLang(lang) {
    document.cookie = 'myCulture=' + lang;
    window.location.reload();
    return false;
}

This will work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.