'How to Increase/Decrease Counter when button is clicked while factoring the value of a dropdown

I have a counter which increases/decreases with +1 when a button is clicked.

The buttons are

  1. Adds Value
<button onClick="onClick()" type="button">ADD MORE</button>
  1. Subtracts From Total Value
<button onClick="onUnClick()" type="button">X</button>

Then the value in H6 changes

<h6 class="askclient">How Many? <a id="clicks">1</a></h6>

My Javascript Code

<script>
    var clicks = 1;
function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML  = clicks;
};
function onUnClick() {
  clicks -= 1;
  document.getElementById("clicks").innerHTML = clicks;
};
</script>

I need to modify it to also add/subtract the value of a select dropdown to the counter so that the total now factors in the text of the dropdown. The dropdown:

<select id="ddlViewBy"  name="repetition[]">
   <option value="1">None</option>
   <option value="2">1</option>
   <option value="3">2</option>
   <option value="4">3</option>
   <option value="5">4</option>
</select>


Solution 1:[1]

You can use onChange to do it.

<h6 class="askclient">How Many? <a id="clicks">1</a></h6>
<button onClick="onClick()" type="button">ADD MORE</button>
<button onClick="onUnClick()" type="button">X</button>
<select id="ddlViewBy"  name="repetition[]" onChange="onChange(this)">
   <option value="0">None</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>
<script>
    var clicks = 1;
    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    function onUnClick() {
        clicks -= 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    function onChange(elem) {
        clicks += Number(elem.value);
        document.getElementById("clicks").innerHTML = clicks;
        document.getElementById("ddlViewBy").selectedIndex = 0;
    }
</script>

Using Number() is required because elem.value is string.

Force back selectedIndex to the None item. Otherwise, if the same number is selected consecutively, onChange will not fire.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Itagaki Fumihiko