0

Can anyone modify this code to [Add by left clicking the number], and [Subtract by right clicking the number]?

This would get rid of the + and - buttons.

I can't figure out how to do it.

DEMO

HTML

<input id="txtNumber" type=text" value="55" style="width:30px" />
<input id="btnAdd" type="button" value="+" onclick="add();" />
<input id="btnSubtract" type="button" value="-" onclick="subtract();" />

Javascript

function add()
{
  var txtNumber = document.getElementById("txtNumber");
  var newNumber = parseInt(txtNumber.value) + 1;
  txtNumber.value = newNumber;
}

function subtract()
{
  var txtNumber = document.getElementById("txtNumber");
  var newNumber = parseInt(txtNumber.value) - 1;
  txtNumber.value = newNumber;
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
user2811882
  • 67
  • 1
  • 2
  • 8
  • Distinguish between left and right click: http://stackoverflow.com/a/2725963/2812842 – scrowler Oct 10 '13 at 21:56
  • Your code seems to work if i return false rather than passing an event param to your context event. http://jsbin.com/oxeyeb/61 Edit: oh.... that's not what you originally had i guess. i hate jsbin for that.. can you include your original code in question?. – Kevin B Oct 10 '13 at 22:03
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Oct 13 '13 at 01:42

1 Answers1

1

This is a good way to do it:

http://jsbin.com/irIwUNi/2/edit

HTML

<input id="txtNumber" type=text" value="55" 
  style="width:30px" onclick="javascript:add()" 
  oncontextmenu="javascript:subtract(event)" />

Javascript

function add()
{
  var txtNumber = document.getElementById("txtNumber");
  var newNumber = parseInt(txtNumber.value) + 1;
  txtNumber.value = newNumber;
}

function subtract(e)
{
  e.preventDefault();
  var txtNumber = document.getElementById("txtNumber");
  var newNumber = parseInt(txtNumber.value) - 1;
  txtNumber.value = newNumber;
  return false;
}

If you just set add() to run on click and subtract() to run on right click (when the context menu would come up), you can capture the click types you want. Then just pass in event to subtract() and stop it from doing what it would normally do, i.e. bring up the context menu.

musicnothing
  • 3,977
  • 24
  • 43