Cameron Howson Cameron Howson - 6 months ago 50
Javascript Question

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. However, it is 3.50 per copy of the complete ebook. So it would have to check the value of number box and times it by the value inside.

Answer

Solution that changes based on checkbox state:

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

printed.addEventListener('change', function(e) {
  var quantity = parseInt(chap7.value, 10);
  
  if (printed.checked) {
    post.value = quantity * 3.5;
  } else {
    post.value = quantity;
  }
}, 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>

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

Comments