3

Hello I'm trying to get value of hidden element in my OOP function. Here is code:

var refreshTimeout;
var rms = new RMS();
rms.refresh();

function RMS() {
    this.refresh = function(){
        alert($("#ids").val());
        $.post(refreshUrl, {ids: $("#ids").val()}, function(response){
            var result = $.parseJSON(response);

            if (result != null) {
                $("#rms").attr("value", result.rms);
            }

            refreshTimeout = setTimeout(function() { rms.refresh(); }, 2000);
        });
    }
}

The problem is that $("#ids").val() works in firebug console but not inside rms.refresh()...

What I'm doing wrong?

1
  • 1
    Is your Javascript inside a document-ready function? Commented Jul 18, 2011 at 7:48

2 Answers 2

1

Your invocation of $('#ids').val() looks fine, so long as the DOM is loaded at this point (i.e. inside a $(document).ready() block).

Your timer function looks a little suspect, though. You're referring to rms which is in the outer scope, when you should be referring to whatever the current object is.

Similarly your timer-related values should be properly encapsulated inside the class, since otherwise you can't have more than one instance.

// class definition - can be loaded anywhere
var RMS = function(ids, rms) {

    var self = this;
    var timer = null;
    var delay = 2000;

    this.refresh = function() {
        $.post(refreshUrl, {ids: $(ids).val()},
            function(response) {
                var result = $.parseJSON(response);
                if (result != null) {
                    $(rms).attr("value", result.rms);
                }

                timer = setTimeout(function() {
                    self.refresh();
                }, delay);
            }
        );
    };
};

// invocation deferred until the DOM is ready
$(document).ready(function() {
   var rms = new RMS('#ids', '#rms');
   rms.refresh();
});
Sign up to request clarification or add additional context in comments.

Comments

0

Try this code:

$(document).ready(function(){
    var refreshTimeout,
        rms = new RMS();

    rms.refresh();

    function RMS() {
        this.refresh = function(){
            $.post(refreshUrl, {ids: $('#ids').val()}, function(response){
                if (typeof(response) != 'undefined') {
                    $('#rms').attr('value', response.rms);
                }
                refreshTimeout = setTimeout(function() { rms.refresh(); }, 2000);
            }, 'json');
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.