简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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