如果选中复选框,则Javascript会添加值

时间:2016-05-09 11:25:04

标签: javascript checkbox

<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。因此,它必须检查数字框的值,并按里面的值计算它。

1 个答案:

答案 0 :(得分:-1)

基于复选框状态更改的解决方案:

&#13;
&#13;
select count(*)
from table(generate_series(1,100000000));
&#13;
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);
});
&#13;
&#13;
&#13;

基于文本输入状态更改的解决方案:

&#13;
&#13;
<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>
&#13;
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);
&#13;
&#13;
&#13;