0

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?

4
  • The issue you are having is only on the setInterval() part? Commented Oct 20, 2015 at 1:16
  • @lucusp yes. i dont see it running just as it was on a the javascript version Commented Oct 20, 2015 at 1:20
  • is it a better approach if i just call the javascript function on the else statement? else{ addTenPercent(); } Commented Oct 20, 2015 at 1:27
  • You can absolutely do that! Commented Oct 20, 2015 at 1:28

2 Answers 2

1

.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.

Sign up to request clarification or add additional context in comments.

Comments

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;

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.