user2811002
user2811002

Reputation: 55

Multiple Plus/Minus boxes

I am using - and + buttons to decrease and increase the number of the text box, where I am having problems is when I use multiple counters on one page

This is the script for one. How can I edit this code so I can use it as many times as i wish on on one page

<script language=javascript>
function process(v){
var value = parseInt(document.getElementById('v').value);
value+=v;
document.getElementById('v').value = value;
}
</script>

<input type=button value='-' onclick='javascript:process(-1)'>
<input type=test size=10 id='v' name='v' value='0'>
<input type=button value='+' onclick='javascript:process(1)'>

Upvotes: 0

Views: 3836

Answers (2)

Jason P
Jason P

Reputation: 27012

Since the question is tagged with jQuery, here's a jQuery answer:

http://jsfiddle.net/pxJHc/

<div>
    <input type='button' value='-' class='minus' />
    <input type='text' size='10' class='value' value='0' />
    <input type='button' value='+' class='plus' />
</div>

$('.minus, .plus').click(function (e) {
    e.preventDefault();    
    var $input = $(this).siblings('.value');
    var val = parseInt($input.val(), 10);
    $input.val(val + ($(this).hasClass('minus') ? -1 : 1));
});

Upvotes: 2

Ayman Gado
Ayman Gado

Reputation: 36

very easy :)

<script language=javascript>
function process(v, target){
    var value = parseInt(document.getElementById(target).value);
    value+=v;
    document.getElementById(target).value = value;
}
</script>

<input type=button value='-' onclick='javascript:process(-1, "v")'>
<input type=test size=10 id='v' name='v' value='0'>
<input type=button value='+' onclick='javascript:process(1, "v")'>

<br />    

<input type=button value='-' onclick='javascript:process(-1, "v2")'>
<input type=test size=10 id='v2' name='v' value='0'>
<input type=button value='+' onclick='javascript:process(1, "v2")'>

Upvotes: 0

Related Questions