提交表单后,javascript中的计时器问题

我正在尝试创建一个计时器倒计时,以根据用户输入的结束日期显示剩余的时间(天:小时:分钟:秒)。日期以以下格式输入:mm / dd / yyyy。

我正在使用以下javascript,并在网页上获取NaN:

// selected text is the date selected on the form on the web page.
var selectedText = document.getElementById('budgetEndingDate').value;
var countDownDate = new Date(selectedText).getTime();

var x = setInterval(function() {

var now = new Date().getTime();

var pending = countDownDate - now;

var days = Math.floor(pending / (1000 * 60 * 60 * 24));
var hours = Math.floor((pending % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((pending % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((pending % (1000 * 60)) / 1000);


// Display the result
document.getElementById("timer").innerHTML = days + "Days " + hours + "Hours " +
    minutes + "Minutes " + seconds + "Seconds ";


// If the count down is finished
if (pending < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "EXPIRED";
}
}, 1000);

HTML是:

    <div id="form1div">
   <form id="form1" class="form-group" action="" method="POST">
      <div class="form-group row">
         <label for="monthly-income" class="col-sm-2 col-form-label"> Monthly Income </label>
         <div class="col-sm-10">
            <input type="number" class="form-control" placeholder="Enter income" name="monthly-income"
               id="monthly-income" required>
         </div>
      </div>
      <div class="form-group row">
         <label for="budgetEndingDate" class="col-sm-2 col-form-label"> Budget ending date </label>
         <div class="col-sm-10">
            <input type="date" class="form-control" id="budgetEndingDate" name="budgetEndingDate" required>
         </div>
      </div>
      <div class="form-group row">
         <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Submit</button>
         </div>
      </div>
   </form>
</div>

问题是selectedText仅在提交表单后才有价值。计时器从启动本身开始运行。因此,countdownDate始终为NaN。 console.log(selectedText)不返回任何内容,因此显示NaN。无法理解如何进行相同操作。

评论