MissCoder87
MissCoder87

Reputation: 2669

Undefined Javascript value

I'm trying to work out if values have changed through javascript. Essentially doing a check on a textbox to see if the value changes.

However, when I put the value in to a variable it comes back as undefined. Clearly i'm doing something silly wrong but my tired head can't work it out.

Here's what i'm doing:

<script>
    var stableCount;
    $(document).ready(function () {
        $('.div-updated').hide();
        $("#responsecontainer").load("CyberTable.aspx");
        stableCount = $(".rowcount").val();
        var refreshId = setInterval(function () {
            alert(stableCount + " - " + $(".rowcount").val())
            $("#responsecontainer").load('CyberTable.aspx?t' + Math.random());
        }, 3000);
        $.ajaxSetup({ cache: false });
    });
</script>

The stableCount in the alert comes back as undefined, but the rowcount.val() comes back with the number

EDIT: Please just don't downvote with no reason. As far as i'm aware i've followed all rules to post this and attempted to do it myself.

Upvotes: 1

Views: 114

Answers (3)

vogomatix
vogomatix

Reputation: 5083

This answer clarifies what I said in my comments. Once you launch a load operation it runs as a separate process and you only know it has loaded the data when a complete or error callback is called. The code needs modifying to have a callback to the load operation, and to start the timer events from within the callback

<script>
$(document).ready(function () {
    $('.div-updated').hide();
    $("#responsecontainer").load("CyberTable.aspx",
       // callback function here....
       function() {
          var stableCount = $(".rowcount").val();
          var refreshId = setInterval(function () {
              alert(stableCount + " - " + $(".rowcount").val())
             $("#responsecontainer").load('CyberTable.aspx?t' + Math.random());
          }, 3000);
    });

    $.ajaxSetup({ cache: false });
});

Upvotes: 1

dkv on
dkv on

Reputation: 9

use stableCount variable in scope of document object. Because stableCount is not global here

<script>
$(document).ready(function () {
    $('.div-updated').hide();
    $("#responsecontainer").load("CyberTable.aspx");
    var stableCount = $(".rowcount").val();
    var refreshId = setInterval(function () {
        alert(stableCount + " - " + $(".rowcount").val())
        $("#responsecontainer").load('CyberTable.aspx?t' + Math.random());
    }, 3000);
    $.ajaxSetup({ cache: false });
});

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26739

the .load is asynchronous. Because of this, $(".rowcount").val() is undefined at the time you assign the stableCount value, but available 3 seconds later in the interval function.

Upvotes: 1

Related Questions