Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase/decrease textfield value with javascript

I'm having trouble in doing a javascript that will do the following:

Increase/decrease number inside textbox when image clicked. setting a limit for that textbox (not below zero, not above x)

please know i have many text boxes in the same page, so how can this issue be fixed?

Image for illustration

like image 282
TDSii Avatar asked Feb 21 '26 12:02

TDSii


2 Answers

You don't need to (and shouldn't) set ids for each and every image and input field. You will need to set name attributes for each input field though (so your server code can tell them apart - but not for JS).

If the "add" section for each row looks like:

<div>
  <img src='minus.png' onclick="increment(this.parentNode.getElementsByTagName('input')[0]);" />
  <input type='text' name='product_1010101011' />
  <img src='plus.png' onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);" />
</div>

use this javascript:

function increment(myInput) {
  // use Mike Samuel's code here
  myInput.value = (+myInput.value + 1) || 0;
}
function decrement(myInput) {
  // use Mike Samuel's code here
  myInput.value = (myInput.value - 1) || 0;
}
like image 165
James Avatar answered Feb 24 '26 14:02

James


I think this should get you going:

<form>
    <input type="button" id="minus" value="-" 
    onClick="textb.value = (textb.value-1)">
    <input type="text" id="textb" name="name" value="1" />
    <input type="button" value="+" 
    onClick="textb.value = (+textb.value+1)">
</form>

Live example here

like image 28
Trufa Avatar answered Feb 24 '26 13:02

Trufa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!