0

Hey I have this line of code

<input id="product_qty" type="text" name="product_qty" value="1" style="color: black">

and what I do is that when I press a button the value of this input change and will add 1, like 1, then 2, etc.

But what I wanted to know is how I get the last value of this input, for example if I pressed five times the button how do I get the number 5 in javascript or using jquery.

I was looking for some information but I couldn't find anything.

Thanks.

Carlos Ortega
  • 13
  • 1
  • 7
  • 4
    I'm not sure exactly what you're asking, but `$('#product_qty').val()` will get you the fields' value. Also it would seem more appropriate given your description to use a `type="number"` field, as it has all the functionality you need built in - an up/down arrow to inc/decrement and `min`/`max` attributes to stop counting above/below a given range – Rory McCrossan Jan 03 '17 at 16:14

6 Answers6

2

In Javascript you can get the las string with substr

var id = document.getElementById("product_qty").value;
var lastChar = id.substr(id.length - 1);
Roy Bogado
  • 4,299
  • 1
  • 15
  • 31
1

I think this will count up the value in the input:

var count = document.getElementById("product_qty").value;
count++;
Wouter den Ouden
  • 1,523
  • 2
  • 17
  • 44
0

You can also use the string as an array and do something like this:

var id = document.getElementById("product_qty").value;
var lastChar = id[id.length -1];
DCruz22
  • 806
  • 1
  • 9
  • 18
0

You can get the last string of strings with a substr http://www.w3schools.com/jsref/jsref_substr.asp

Wouter Schoofs
  • 966
  • 9
  • 13
0

If I understand your question correctly, then you already have a click event on your button that increments your input's value by 1 on each click.

Just get the value in that same click event.

$('#yourButton').on('click', function(e) {
  // increment input by 1
  $('#product_qty').get(0).value++;
  // logging out your value - use it however you want
  console.log('my input value: ', $('#product_qty').val());
)};
Sean
  • 267
  • 4
  • 9
0

Think you looking for something like this:

$(function(){
    $('#button').click(function() {
    var val =  Number($('#product_qty').val());
    val++;
    $('#product_qty').val(val);
  });
})

Fiddle: https://jsfiddle.net/k1wkqekf/

JavaKungFu
  • 1,264
  • 2
  • 11
  • 24