4
$(document).ready(function() {

    var x = "";

    $("#anyElement").click(function() {
        x = "test";
        alert(x);
    });

    alert(x);
});

When first alert works, messagebox shows "test". when second alert works, messagebox shows " ".

$("#anyElement").click(function() {
    // How can i set the x veriable as "test" here
});
Huangism
  • 16,278
  • 7
  • 48
  • 74
Ahmet
  • 314
  • 5
  • 15
  • 2
    Code looks fine...are you sure the first alert isn't `""`? – tymeJV Oct 27 '14 at 19:55
  • This is due to scope of variable. – Apul Gupta Oct 27 '14 at 19:55
  • I mean as saying firs : the upper alert :) – Ahmet Oct 27 '14 at 19:56
  • 2
    Your code works as expected. The code within the click handler does not run until a click event actually occurs. – PeterKA Oct 27 '14 at 19:57
  • 1
    Please provide more information. This code seems to be running good. What exactly are you trying to accomplish? it sounds like you want your result to be the complete opposite of what you have. youre probably trying to access the X variable from outside of $(document).ready – CodeGodie Oct 27 '14 at 20:01
  • I just want to set x veriable "test" in the click event. And i success it but when click event overed, x happens " " again – Ahmet Oct 27 '14 at 20:13

3 Answers3

2

I'm not sure if I understand what are you asking for, but hey, let's avoid globals, shall we?

That said, I would suggest you to try an approach like this:

var app = {};
app.x = 'initial value';

app.bindEvents = function() {
    $('#anyElement').click(function() {
        app.x = 'test';
        console.log(app.x);
    });    
};
app.bindEvents = function() {
    app.bind();
};
$(app.init);

Here, our code is only setting one global object (app), avoiding polluting the namespace. The problem in your code was that you were trying to set a "global" but that x wasn't a global, but just a local variable.

See a working JSFiddle here

Rafael Eyng
  • 4,720
  • 2
  • 33
  • 34
0

Your code is working as expected, the first alert is empty because the click trigger hasn't been called:

FIDDLE

$(document).ready(function() {

    var x = "";

    $("#anyElement").click(function() {
        x = "test";
        alert(x);
    });

    alert(x);
});
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
0

The problem you are experiencing is because of the flow of the program. Your declaration of the variable x makes x global and scoped to the document.ready function.

'test' is not assigned to the x variable until after the click event and the first alert is actually the second alert written in the code because there is no event associated with the alert.

morissette
  • 1,071
  • 1
  • 8
  • 29
  • just being nit-picky... if x is scoped, then it isn't global. If you tried `alert(x)` outside of document.ready, you would get undefined. – Brian Glaz Oct 27 '14 at 20:04