Прогресс бар для формы - PullRequest
0 голосов
/ 17 марта 2020

Я пытаюсь создать индикатор выполнения для моей формы, но он все еще не работает. После загрузки формы я бы хотел, чтобы индикатор выполнения переместился с 0 процентов до 100 и завершил загрузку sh. Я до сих пор не понимаю, почему мой индикатор не работает.

Мой код выглядит так

<form method="POST" enctype="multipart/form-data" name="newProductForm" id="newProductForm">
  <input type="file" name="img" class="custom-input-file" accept=".jpg, .jpeg" required id="id_img">
  <input type="text" name="category" class="form-control form-control-emphasized" id="category" placeholder="Wpisz kategorie..." maxlength="200" required>

  <div class="progress">
    <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
      0%
    </div>
  </div>

  <button type="button" onClick="submitFunction();" class="btn btn-block btn-primary" id="buttonSubmitProduct">
    <span style="display:block;" id="buttonText">
      Submit
    </span>
    <span style="display:none;" id="buttonSipner">
      Loading......
    </span>
  </button>

</form>

My AJAX и JS:

<script>
function submitFunction() {
  document.getElementById('buttonSubmitProduct').disabled = true;
  document.getElementById('buttonText').style.display = 'none';
  document.getElementById('buttonSipner').style.display = 'block';
  document.getElementById('newProductForm').submit();
}

$(document).ready(function() {

  $('newProductForm').on('submit', function(event) {

    event.preventDefault();

    var formData = new FormData($('newProductForm')[0]);

    $.ajax({
      xhr: function() {
        var xhr = new window.XMLHttpRequest();

        xhr.upload.addEventListener('progress', function(e) {

          if (e.lengthComputable) {

            console.log('Bytes Loaded: ' + e.loaded);
            console.log('Total Size: ' + e.total);
            console.log('Percentage Uploaded: ' + (e.loaded / e.total))

            var percent = Math.round((e.loaded / e.total) * 100);

            $('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');

          }

        });

        return xhr;
      },
      type: 'POST',
      url: '',
      data: formData,
      processData: false,
      contentType: false,
      success: function() {
        location.replace("/?okey=smile");
      }
    });

  });

});
</script>

Я не вижу ошибок в консоли. Почему мой код не работает?

1 Ответ

1 голос
/ 17 марта 2020

Как насчет использования тега прогресса HTML5 для этого?

//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
     var pos = 0; 

    var t = setInterval(move, 75);
  
    function move() {
        if(pos >= 400) {
            clearInterval(t);
        }
        else {
            pos += 4;
            bar.value = pos/4;
        }
    }
};
#container {
    width: 400px;
    height: 50px;
    position: relative;

}

#bar {
    width: 400px;
    height: 50px;
    position: absolute;
}

progress {
  text-align: center;
}
progress:after {
  content: attr(value)'%';
}

progress:before {
  content: 'progress ';
}
<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
	<div id="container">
	<progress id="bar" value="0" max="100"></progress>
            
        </div>
       
	</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...