javascript - Input's value as variable is not defined - Stack Overflow

Got an input type text. Whatever entered is supposed to bee a value for variable, and further on from t

Got an input type text. Whatever entered is supposed to bee 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();
});

Got an input type text. Whatever entered is supposed to bee 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();
});
Share Improve this question asked Jun 4, 2015 at 0:39 Vici AVici A 831 silver badge6 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 2

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));

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);
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745235169a4617856.html

相关推荐

  • javascript - Input&#39;s value as variable is not defined - Stack Overflow

    Got an input type text. Whatever entered is supposed to bee a value for variable, and further on from t

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信