admin管理员组

文章数量:1289911

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?

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?

Share Improve this question edited Mar 11, 2011 at 21:42 Peter Olson 143k49 gold badges208 silver badges249 bronze badges asked Mar 11, 2011 at 21:37 TDSiiTDSii 1,7254 gold badges21 silver badges29 bronze badges 2
  • are you using any kind of library? – Rodolfo Palma Commented Mar 11, 2011 at 21:46
  • i tried jquery but i was looking for more simpler approach. – TDSii Commented Mar 11, 2011 at 21:59
Add a ment  | 

3 Answers 3

Reset to default 6

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

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

To increment

myInput.value = (+myInput.value + 1) || 0;

To decrement

myInput.value = (myInput.value - 1) || 0;

The || 0 will reset any value that doesn't parse as an integer to a default value, 0.

本文标签: imageIncreasedecrease textfield value with javascriptStack Overflow