0

I have these two forms:

<select name="services" id="services">
  <option value="240" id="option1">full repair</option>
  <option value="70" id="option2">cleaning</option>
  <option value="50" id="option3">correction</option>
</select>

<label for="delivery1"> 0 $: </label>
<input type="checkbox" id="delivery2" name="delivery" value="0"><br/>
<label for="delivery2"> 50 $: </label>
<input type="checkbox" id="delivery2" name="delivery" value="50"><br/>
<label for="delivery3"> 150 $ : </label>
<input type="checkbox" id="delivery3" name="delivery" value="150">

and this button with onClick attribute:

<input type="submit" id="button" value="Submit" onclick="calculatePrice()">

Upon clicking the button, the function calculatePrice is supposed to add the value of the selected <select> option and the checked "delivery" option, I have this code:

function calculatePrice() {
  var sel = document.getElementById("services");
  var opt = sel.options[sel.selectedIndex].value;
  const checkboxes = document.querySelectorAll('input[name="delivery"]:checked');
  let deliveries = [];
  checkboxes.forEach((checkbox) => {
    deliveries.push(checkbox.value);
  });
  var price = opt + deliveries;
  document.getElementById("result").innerHTML = "Thank you for the interest in our service, the full price is: " + price + " $"
}

However, it is not adding the values up, instead it's lising them, for example 70150 instead of 70+150=220, how can I fix it?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
peroo
  • 17
  • 2
  • Try: `deliveries.push(parseInt(checkbox.value, 10))` – Mr. Polywhirl May 24 '21 at 15:31
  • Alternatively, you could try: `deliveries.push(checkbox.valueAsNumber)`. For more info, see: [`HTMLInputElement.valueAsNumber`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) – Mr. Polywhirl May 24 '21 at 15:36

0 Answers0