Dren
Dren

Reputation: 319

jquery equivalent of javascript interval function

I have this javascript function

function addTenPercent(){
        var bar = document.getElementById("progressBar");
        setInterval(addTenPercent, 5000);
        bar.value += 10;
};

I am trying to include it on my jquery if else statement but with no luck

$('#form1').submit(function(e){
        if ($.trim($('#store').val()) === "" || $.trim($('#store').val()) === "Enter store number'(nnnn)'") {
                e.preventDefault();
                alert('Please type in store number');
        }
        else {
                setInterval(function(){
                $('#progressBar').val() += 10;
                },5000);
        }
});

Can someone help point where did i go wrong on converting the said javascript to jquery?

Upvotes: 0

Views: 146

Answers (2)

guest271314
guest271314

Reputation: 1

$('#progressBar').val() += 10; not appear to set , reset value of element ?

.val() returns value of element ; += 10 not called as argument to .val() on element .

To set value of element , could use

$('#progressBar').val( $('#progressBar').val() += 10 );

or use .val(function(index, value) {})


Try substituting

$('#progressBar').val(function(_, v) {
  return v += 10
})

for

$('#progressBar').val() += 10;

Upvotes: 1

Igor Raush
Igor Raush

Reputation: 15240

.val() returns the current value of the element, and you cannot modify the value by reference. guest271314's answer will work, but since it's good practice to cache your jQuery selections anyway, I suggest the following solution:

var progressBar = $('#progressBar')[0];
setInterval(function () {
    progressBar.value += 10;
}, 5000);

Notice that progessBar is a raw DOM element, not a jQuery object, and progressBar.value is being accessed by reference.

Upvotes: 1

Related Questions