简体   繁体   English

如果复选框被选中,Javascript 添加值

[英]Javascript add value if checkbox is checked

<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>

I would like a piece of javascript so that upon the checkbox being checked, it makes the postage value 3.50.我想要一段javascript,以便在选中复选框时,邮资值为3.50。 However, it is 3.50 per copy of the complete ebook.但是,完整电子书的每份 3.50 美元。 So it would have to check the value of number box and times it by the value inside.所以它必须检查数字框的值并按里面的值对其进行计时。

Solution that changes based on checkbox state:根据复选框状态更改的解决方案:

 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>


Solution that changes based on text input state:根据文本输入状态变化的解决方案:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM