Search code examples
javascripthtmljquerycssprogress-bar

How do I create a Progress bar using the value of an ID


Before the code below, a user enters the title of a book they read. There is then a total count automatically populated in id="bookcount".

I have a progressbar for the book count, but how can I make it automatically grab the number in bookcount...so the progress bar can update as more books are entered. (Basically, value="2" needs to somehow pull the number instead of manually assigning the value.)

<div id="bookcount">2</div>
<label for="bookprogress">progress:</label>
<progress id="bookprogress" max="5" value="2"> 70% </progress>

JS

$(document).ready(function(){ 
    $("#bookprogress").val("#bookcount");
});

Solution

  • Get the number with var bookCount = +$('#bookcount').text() and then set it using $('#bookprogress').attr('value',bookCount);.

    First line of code takes content of a div and casts it to the number using simple + in front of it. The other line just sets the value of the progress bar to the div value.

    var bookCount = +$('#bookcount').text()
    $('#bookprogress').attr('value',bookCount);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="bookcount">2</div>
    <label for="bookprogress">progress:</label>
    <progress id="bookprogress" max="5" value="0"> 70% </progress>