John Does Legacy John Does Legacy - 7 months ago 22
Javascript Question

Jquery / Javascript Progressbar blue

I am trying to built a simple progressbar, but got some problems.

Html looks like this:

<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:0%"></div>
</div>


And my javascript like this:

$("input").blur(function(){
var progressbar = $('.progress-bar');
if($(this).val().length > 0 && !$(this).is("filled")) {
progressbar.width(progressbar.width() + 40);
$(this).addClass("filled");
} else if ($(this).val() == '' && $(this).is(".filled")) {
progressbar.width(progressbar.width() - 40);
$(this).removeClass("filled");
}
});


So basically I write something in my input field and click out and my progressbar increases.

If the input field returns to empty after it was filled the progressbar decreases.

The problem is now that I keep clicking in and out on a not empty input and the progressbar keeps increasing.

Fiddle:

Demo Code

Answer

I have updated your fiddle: https://jsfiddle.net/1a8qcgdc/5/ and instead of:

var isfilled = 0;

I added a class nowFilled, hope it helps

 var isfilled = 0;

 $("input").change(function() {
   $(this).blur(function() {
     var progressbar = $('.progress-bar');

     if ($(this).val().length > 0 && !$(this).is("filled") && !$(this).hasClass('nowFilled')) {
       //isfilled = 1;
       $(this).addClass('nowFilled')
       progressbar.width(progressbar.width() + 40);
       $(this).addClass("filled");
     } else if ($(this).val() == '' && $(this).is(".filled")) {
       progressbar.width(progressbar.width() - 40);
       $(this).removeClass('nowFilled')
       //isfilled = 0;
       $(this).removeClass("filled");
     }
   });
 })
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="progress">
  <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:0%">
  </div>
</div>

<input type="text" class="form-control" name="project_name">
<input type="text" class="form-control" name="asd">