given new input in textbox is not updating in progress bar

时间:2018-02-03 09:12:00

标签: javascript html css

<script>
    function move() {
        var dolar= document.getElementById("no1").value;   
        var elem = document.getElementById("myBar");   
        // var width = parseInt(dolar);
        var width = 500;
        var id = setInterval(frame, 5000);
        function frame() {
           width=parseInt(width)+parseInt(dolar);   
           if(width>=5000) {
               clearInterval(id);
           }
        elem.style.width = width + 'px'; 
        elem.innerHTML = width * 1  + 'px';
      }
   }
</script>

//the first input will increment in progress bar but the updated value would not get update in progress bar//

2 个答案:

答案 0 :(得分:1)

Use this fiddle

I think its solve your problem...

function move() {
  var dolar= document.getElementById("no1").value;   
  var elem = document.getElementById("myBar");   
  var width = 500;
  var id = setInterval(frame, 5000);
  function frame() {
    width=parseInt(width)+parseInt(dolar);   
    if(width>=5000) {
      clearInterval(id);
    }
    elem.style.width = width + 'px'; 
    elem.innerHTML = width * 1  + 'px';
  }
}
move();

答案 1 :(得分:0)

Issues I found in this code snippet are as follows:

  1. Updated value in input is not being added in "width".
  2. "NaNpx" is displayed as value of "myBar" when input "no1" is empty.

To address above issues,

  1. Pull definition of "dolar" inside "frame" function.
  2. Just add undefined/null check before adding "dolar" in "width"

Below code should work fine:

<script>
    function move() {
        var dolar;
        var elem = document.getElementById("myBar");
        var width = 500;
        var id = setInterval(frame, 5000);
        function frame() {
           dolar = document.getElementById("no1").value;
           width = width + (!dolar ? 0 : dolar * 1);
           if (width >= 5000) {
               clearInterval(id);
           }
           elem.style.width = width + 'px'; 
           elem.innerHTML = width + 'px';
        }
    }
    move()
</script>