e.iluf
e.iluf

Reputation: 1659

getting html user generated input is not working

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?

Upvotes: 4

Views: 65

Answers (3)

zdarkwhite
zdarkwhite

Reputation: 366

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);
}

Upvotes: 3

S&#233;bastien
S&#233;bastien

Reputation: 12139

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();

Upvotes: 1

mep2664
mep2664

Reputation: 102

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

Upvotes: 1

Related Questions