Vici A
Vici A

Reputation: 83

Input's value as variable is not defined

Got an input type text. Whatever entered is supposed to become a value for variable, and further on from there. Yet, i get error "Uncaught ReferenceError: emailvar is not defined" and the whole script breaks from there.

html

<input type="text" class="signfield emfield" />
<div class="submt sbmtfrm" href="#" style="cursor:pointer;">Step 2</div>

and js

$(".sbmtfrm").click(function(){
   var emailvar = $(".emfield").val();
});

Upvotes: 0

Views: 7211

Answers (2)

honyovk
honyovk

Reputation: 2747

In your code, emailvar is being defined in a function closure, and only that function has access to it.

$(".sbmtfrm").click(function(){
   var emailvar = $(".emfield").val();
});

If you want to use emailvar outside of your jQuery event handler, you will need to first define it (not assign it, yet) outside the scope of the function.

(function(window, $) { // closure
    var emailvar;

    $(".sbmtfrm").click(function() {
        emailvar = $(".emfield").val();
    });

    // you now have access to `emailvar` in any function in this closure

}(window, jQuery));

Upvotes: 2

user2684182
user2684182

Reputation:

You need to declare emailvar as a global variable to use it outside of that click event handler:

$(function()
{
    var emailvar;
    $(".sbmtfrm").click(function()
    {
       emailvar = $(".emfield").val();
    });
    function foo()
    {
        console.log(emailvar);
    }
}

Upvotes: 2

Related Questions