2

i already have this code but it does not work as expected.

the word "piece" should be changed to "pieces" when the quantity is greater than 1.

<span class="counter b">2 <span id="unitpcs"></span></span>

<script type="text/javascript">

var q = document.getElementsByTagName("span");
var a = myFunction(q.innerHTML);
document.getElementById("unitpcs").innerHTML = x;

function myFunction() {
if (a > 1) {
        x = "pieces";
    } else {
        x = "piece";
    }
}
</script>

Currently, when the quantity is equal to one (1), the result is correct: 1 piece.

If the quantity becomes two (2), the result is not correct: 2 piece The correct output should be "2 pieces".

Any solution is highly appreciated. Thanks in advance!

jaidsis
  • 23
  • 3
  • 1
    Please state your question a bit clearer https://stackoverflow.com/help/how-to-ask – David Baak Sep 25 '18 at 09:24
  • For example: when the quantity is one (1), the output should be 1 item. then, if the quantity is greater than 1, e.g. 2 items, 3 items, and so on. – jaidsis Sep 25 '18 at 09:32
  • Hi @jaidsis, please update your question with this comment. Also try to explain what is the current behavior and what you would expect instead. – toti08 Sep 25 '18 at 09:40
  • Hi @toti08, i already updated the question above. – jaidsis Sep 25 '18 at 10:06

1 Answers1

2
  1. You forgot to specify a as the parameter of myFunction().
  2. You overlooked that q is an array of two span elements.
  3. You neglected to convert the .innerHTML to a number.

<span class="counter b">2 <span id="unitpcs"></span></span>

<script type="text/javascript">
var q = document.getElementsByTagName("span");
myFunction(parseFloat(q[0].innerHTML)); // first span, convert to number
document.getElementById("unitpcs").innerHTML = x;

function myFunction(a) {
if (a > 1) {
        x = "items";
    } else {
        x = "item";
    }
}
</script>
Armali
  • 18,255
  • 14
  • 57
  • 171