4

I have a quantity selector where user click on plus or minus to increase or decrease the number.

function initQuantity() {
  if ($('.plus').length && $('.minus').length) {
    var plus = $('.plus');
    var minus = $('.minus');
    var value = $('#quantity_value');

    plus.on('click', function() {
      var x = parseInt(value.text());
      value.text(x + 1);
    });

    minus.on('click', function() {
      var x = parseInt(value.text());
      if (x > 1) {
        value.text(x - 1);
      }
    });
  }
}

initQuantity();
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Quantity:</span>
<div class="quantity_selector">
  <span class="minus"><i class="fa fa-minus" aria-hidden="true"></i></span>
  <span id="quantity_value">1</span>
  <span class="plus"><i class="fa fa-plus" aria-hidden="true"></i></span>
</div>

Everything works fine. I need to do two things; set a maximum for quantity_value and get the user value. I tried this for getting the user value

var qty = document.getElementById("quantity_value").value;

but what i get is:

undefined

How can I implement getting the user-incremented value and setting the maximum for the quantity selector?

2
  • 4
    span doesn't have 'value' property, use textContent. Commented Dec 29, 2017 at 18:09
  • jsfiddle.net/DanielGale/joq9gm5q/2 You shouldn't need parseInt if you are controlling the number in the span. Commented Dec 29, 2017 at 18:34

3 Answers 3

3

You already have the quantity_value in

var x = parseInt(value.text());

You can apply your validation before the update

value.text(x + 1);

Like this

if(x <= MAXIMUM_VALUE){
    value.text(x + 1);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed, nice catch. No need to fetch it from the HTML again. In fact, I might define the variable as "1" and insert it into the HTML in the first place.
1

It is returning undefined because span elements don't have the value property you are trying to access. The following should work in modern browsers...

var qty = document.getElementById("quantity_value").textContent;

This is similar to this question

1 Comment

or, as they're using jQuery elsewhere, $("#quantity_value").text();
1

You are already using jQuery so take advantage of it instead of using document.getElementById("quantity_value") you can use a jQuery selector.

Also as @sinisake pointed out you must access the text content, not the value as span elements don't have a value attribute:

var qty = $('#quantity_value').text();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.