【问题标题】:Javascript add value if checkbox is checked如果选中复选框,则Javascript添加值
【发布时间】:2016-09-04 00:25:25
【问题描述】:
<p>
    <label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
    <input type="number" min="0" id="chap7" name="hours" value="0">
</p>

<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />

<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>

我想要一段 javascript,以便在选中复选框后,邮资值为 3.50。但是,完整的电子书每份是 3.50。所以它必须检查数字框的值,并用里面的值来计时。

【问题讨论】:

  • @Malik 我对javascript不太好,所以只有 if(document.getElementById('printed').checked){ document.getElementById('post').value + 3.50 }
  • var total = parseInt(document.querySelector('#chap7').value, 10) * 3.5;
  • "我想要一段 javascript" -- StackOverflow 不是编码服务

标签: javascript checkbox


【解决方案1】:

根据复选框状态改变的解决方案:

var chap7 = document.getElementById('chap7'),
    post = document.getElementById('post'),
    printed = document.getElementById('printed');

printed.addEventListener('change', function() {
  var quantity = parseInt(chap7.value, 10);
  
  post.value = printed.checked ? quantity * 3.5 : quantity;
}, false);

chap7.addEventListener('change', function() {
  post.value = parseInt(this.value, 10);
});
<p>
    <label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
    <input type="number" min="0" id="chap7" name="hours" value="0">
</p>

<input type="checkbox" id="printed"/>Please tick if you would like a printed version<br />

<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>

根据文本输入状态变化的解决方案:

var chap7 = document.getElementById('chap7'),
    post = document.getElementById('post');

chap7.addEventListener('change', function(e) {
  var quantity = parseInt(chap7.value, 10);
  
  post.value = quantity * 3.5;
}, false);
<p>
    <label for="hours">Learn JavaScript the Hardy Way’ - Complete e-book (Printed)</label>
    <input type="number" min="0" id="chap7" name="hours" value="0">
</p>
<p class="post">Postage : <strong>£<output id="post">0</output></strong><p>

【讨论】:

  • 这很好用,我如何在不涉及复选框的情况下将其重新用于另一部分?
  • 对不起,我以为我已经说得很清楚了,确切地说它是如何工作的,但复选框没有监听器。所以 numberbox 的值本质上是 3.50。
  • @CameronHowson,我添加了另一个解决方案。
  • 非常感谢,您的帮助非常大
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 2014-02-21
  • 1970-01-01
  • 2020-09-11
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多