Progress Bar to follow input text

Asked

Viewed 290 times

4

Well I’m starting in Bootstrap and I’m having a doubt whether or not it’s possible that I’m wanting. I have a textarea where it must limit the content to 300 characters it is already working:

$(function(){
   $(".maxlength").keyup(function(event){
     var target    = $("#content-countdown");
     var max        = target.attr('title');
     var len     = $(this).val().length;
     var remain    = max - len;
     if(len > max)
     {
       var val = $(this).val();
       $(this).val(val.substr(0, max));
       remain = 0;
     }
     target.html(remain);
   });
});


Html:

Restam <span id="content-countdown" title="300">300</span>Caracteres) 
<textarea name="texto" id="content" class="maxlength" maxlength="300" cols="60" rows="5"></textarea>

But I would like that instead of decreasing the number, the progress bar increases as the text is being typed and if it reaches 100% (300 characters) block any more digits. Any idea or simpler way to do this?

1 answer

5


In HTML5 there is an element called progress, you can use it to achieve your goal:

$(function(){
$(".maxlength").keyup(function(event){
document.getElementById("progress").value = $(this).val().length;
var target    = $("#content-countdown");
var max        = target.attr('title');
var len     = $(this).val().length;
var remain    = max - len;
if(len > max)
{
var val = $(this).val();
$(this).val(val.substr(0, max));
remain = 0;
}
target.html(remain);
});
});
progress {
background-color: #f3f3f3;
border: 0;
height: 18px;
border-radius: 9px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Restam <span id="content-countdown" title="200">200</span>Caracteres)<br/>
<textarea name="texto" id="content" class="maxlength" maxlength="200" cols="60" rows="5"></textarea><br/>
<progress id="progress" max="200"></progress>

  • very practical this function, I thought it would be quite complicated this, congratulations

  • 1

    Because this Progress element is HTML5, it won’t work in some older browsers.... just keep this in mind

  • 2

    A suggestion is to use keypress instead of keyup. In the case of keyup to view will be updated only when the user stops pressing any key, if he keeps the key pressed nothing will happen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.