首页 > 解决方案 > 我创建了专注的功能,但验证功能首先运行?使用 DOMLoaded 内容

问题描述

如果输入了无效条目,我创建了一个函数来重新关注输入框。但是,当我单击输入框时,它会运行该validate()函数。此后它确实聚焦,但它在它应该运行之前运行该功能。我确信我做错了什么,但是,我仍然在努力解决 DOM 加载的内容是如何工作的。

我复制了下面的代码:

window.addEventListener('DOMContentLoaded', () => {
  document.getElementById("principal").addEventListener('click', function(event) {
    event.preventDefault();
    validate();
  });
})

function validate() {
  var num = document.myform.num.value;
  if (isNaN(num) || num == 0 || num < 0 || num == null) {
    alert("Please enter a valid entry")
    document.getElementsById("principal").focus();
  } else {
    return true;
  }
}
<form name="myform" onsubmit="validate()">
  Amount <input name="num" id="principal" onsubmit=""><br/> </form>
<br>

标签: javascript

解决方案


使用更改事件,不要使用警报。这真的很烦人。由于您坚持,我在提交时将其重新添加

preventDefault 仅在提交时才需要

const validate = (e) => {
  const field = document.getElementById("principal");
  const num = field.value;
  const err = document.getElementById(field.id+"Error");
  err.setAttribute("hidden",true);
  if (isNaN(num) || num == 0 || num < 0 || num == null) {
    field.focus();
    field.select();
    if (e.type==="submit") { 
      alert(err.textContent)
      e.preventDefault()
    }  
    else  err.removeAttribute("hidden");
  }
}
window.addEventListener('load', () => {
  document.getElementById("principal").addEventListener('change', validate)
  document.getElementById("form1").addEventListener('submit', validate)
})
<form id="form1">
  Amount <input name="principal" id="principal" required> <span id="principalError" hidden>Please enter a valid entry</span><br/>
</form>

更简单:

<form name="myform">
  Amount <input name="num" id="principal" type="number" min="1" required autocomplete="off"/>
</form>

添加到您的计算器

const highlight = str => `<span class="highlight">${str}</span>`;
const currency = num => new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
}).format(num);

const getFutureValue = (principal, rate, year) => {
  var interest = rate / 100 + 1;
  return currency(principal * Math.pow(interest, year))
}

const compute = () => {
  // Ensure all values are _numbers_
  p = +document.getElementById("principal").value;
  r = +document.getElementById("rate").value;
  n = +document.getElementById("years").value;

  const newDate = new Date();
  newDate.setFullYear(newDate.getFullYear() + n);
  document.getElementById("result").innerHTML = `If you deposit ${highlight(currency(p))} at an interest rate of ${highlight(r+"%")},<br>
  you will receive an amount of ${highlight(getFutureValue(p, r, n))} in the year ${highlight(newDate.getFullYear())}`;

};


const validate = (e) => {
  const submitting = e.type === "submit"
  if (submitting) e.preventDefault()
  const field = document.getElementById("principal");
  const num = field.value;
  const err = document.getElementById(field.id + "Error");
  err.setAttribute("hidden", true);
  if (isNaN(num) || num == 0 || num < 0 || num == null) {
    field.focus();
    field.select();
    if (submitting)alert(err.textContent)
    else err.removeAttribute("hidden");
    return false;
  }
  return true;
}
window.addEventListener('load', () => {
  document.getElementById("principal").addEventListener('change', validate)
  document.getElementById("form1").addEventListener('submit', function(e) {
    if (validate(e)) compute(); // pass the event
  })
})
.highlight {
  background-color: yellow;
}

#rate,
#years {
  width: 50px
}
<form id="form1">
  $<input type="number" id="principal" /> at <input type="number" id="rate" />% for <input type="number" id="years" /> years
  <br/><span id="principalError" hidden>Please enter a valid amount</span>

  <button id="compute">Compute Interest</button>
</form>
<p id="result"></p>


推荐阅读