Adam Mikó
Adam Mikó

Reputation: 13

Javascript return value undefined

I would like to ask how to return variable 'get_cookies' from function 'save_value'. Then write its value in mouseleave event.

Function 'get_cookies' will save change from input. An error is in return i think.

Sorry for my bad English.

Here is code:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="jquery.cookie.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            function save_value(value) {
                var get_cookie = value;
                return get_cookie;
            };

            $('#submit_value').live('click', function() {
                var get_value = $('#get_value').val();
                save_value(get_value);
            });

            $(document).mouseleave(function() {
                var create_cookie = save_value();
                console.log('save: ' + create_cookie);
            });
        });
    </script>
</head>
<body>
    <input type="text" id="get_value" />
    <input type="button" id="submit_value" value="Click" />
    <div></div>
</body>

console log:

save: undefined

Thx for answer.

Upvotes: 1

Views: 2094

Answers (4)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

It's quite simple: your function function save_value(value) takes the value parameter, assigns it to a variable, and returns that variable. When you call it without parameters, like you do here: var create_cookie = save_value();, the value argument will be undefined. Hence, the function returns undefined.

Also: using variables called cookie doesn't set a cookie. For that, you'll have to use localStorage.setItem('cookieName','cookieValue');

Upvotes: 1

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

Since you are using latest jQuery version, you should not use live() function, since it has been deprecated in jQuery 1.7.

Anyway, your issue is different. Your save_value function does nothing. Just creating a variable and returning its value. But you do not pass any arguments, so it returns default value: undefined.

Upvotes: 0

Timm
Timm

Reputation: 12753

Your save_value() function requires an input parameter, so just save_value() on its own is undefined.

Did you mean to do this?

$(document).mouseleave(function() {
    var get_value = $('#get_value').val();
    var create_cookie = save_value(get_value);
    console.log('save: ' + create_cookie);
});

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

the function save_value() is expecting a parameter. Since here

var create_cookie = save_value();

you're not passing a value to the function, it will return undefined, thus the variable create_cookie value is undefined too

Upvotes: 4

Related Questions