Getting html user input not working

I have a quantity selector where the user clicks 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>
Run code

Everything works perfectly. I need to do two things; set maximum for quantity_valueand get user value. I tried this to get user value

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

but I get:

undefined

How can I implement getting a user-increased value and set the maximum value for the quantity selector?

+4
source share
3 answers

You already have value_value in

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

You can apply your check before updating.

value.text(x + 1);

Like this

if(x <= MAXIMUM_VALUE){
    value.text(x + 1);
}
+3
source

undefined, span value, . ...

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

+1

You are already using jQuery to use it, instead of using document.getElementById("quantity_value")you can use the jQuery selector.

Just as @sinisake pointed out that you should access text content and not as a value span, elements do not have a value attribute:

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

Source: https://habr.com/ru/post/1691518/


All Articles