如何检索表单值,对该表单值执行操作并在<p>标记中显示?

我想从表单控件类型=“数字”中获取一个数字,将其进行比较,然后如果条件确定,则对其进行乘法和除法。之后,我想将结果显示为<p>标签的内容。如何做到这一点?


到目前为止,这是我尝试过的:


let amount = document.getElementById(".amount");

let marginAmount = document.getElementById(".marginAmount")

let submit = document.getElementById(".submit");

submit.addEventListener('click', calcAmount);


const calcLevel1 = amount * 7 / 100;


function calcAmount() {

  let userAmount = Number(amount.value);

  let level1 = 351;

  if (userAmount <= level1) {

    marginAmount.textContent = calcLevel1.value;

  }

}

<div class="form">

  <label for="points amount">Entrez un montant en points</label>

  <input type="number" class="amount-enter" id="amount">

  <input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter">

</div>

<p id="marginAmount" class="enter-margin"></p>


芜湖不芜
浏览 177回答 2
2回答

郎朗坤

这是已更正的代码,有。我还添加math.round了哪些要删除的内容以获得四舍五入的结果:<html><head>&nbsp; <script>&nbsp; &nbsp; function calcAmount() {&nbsp; &nbsp; &nbsp; let userAmount = document.getElementById("amount").value;&nbsp; &nbsp; &nbsp; let level1 = 351;&nbsp; &nbsp; &nbsp; if (userAmount <= level1) {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("marginAmount").textContent = Math.round(userAmount * 7) / 100;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("marginAmount").textContent = "Amount is > 351";&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; </script></head><body>&nbsp; <div class="form">&nbsp; &nbsp; <label for="points amount">Entrez un montant en points</label>&nbsp; &nbsp; <input type="number" class="amount-enter" id="amount">&nbsp; &nbsp; <input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter" onclick="calcAmount()">&nbsp; </div>&nbsp; <p id="marginAmount" class="enter-margin"></p></body>

慕桂英4014372

三件事:您.在ID选择器中没有这些选择器(它们应该存在,#但只能在一种querySelector方法中使用)。您正在calcLevel1直接计算,这意味着0 * 7 / 100是0。你需要计算calcLevel1用amount.value,这意味着你可以删除calcLevel1.value,当你设置textContent的段落。我还添加了一条else语句,以便textContent在该语句为false时将其清空。let amount = document.getElementById("amount");let marginAmount = document.getElementById("marginAmount")let submit = document.getElementById("submit");submit.addEventListener('click', calcAmount);function calcAmount() {&nbsp; const calcLevel1 = amount.value * 7 / 100;&nbsp; let userAmount = Number(amount.value);&nbsp; let level1 = 351;&nbsp; if (userAmount <= level1) {&nbsp; &nbsp; marginAmount.textContent = calcLevel1;&nbsp; } else {&nbsp; &nbsp; marginAmount.textConten = "";&nbsp; }}<div class="form">&nbsp; <label for="points amount">Entrez un montant en points</label>&nbsp; <input type="number" class="amount-enter" id="amount">&nbsp; <input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter"></div><p id="marginAmount" class="enter-margin"></p>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript