Forum Moderators: open

Message Too Old, No Replies

Javascript and Input Fields

How to automaticall change an input onclick

         

wfernley

2:12 pm on Dec 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey everyone.

I am trying to find a tutorial on how to have an onclick event where when the users clicks a button with a plus sign, it will automatically change the number in an input field.

Basically, I have a shopping cart and I want to have the option where there is a minus sign on the left of the input, then in the input is the quantity and then on the right is a plus sign. When the user hits the minus sign the quantity gets lowered by one, and when clicking the plus sign 1 will be added to the quantity.

Does anyone know how to do this, or know where I can find a tutorial on this? I tried looking but didn't find anything. I wasn't sure what it was called though so that could be why nothing showed up.

Thanks in advance for your help!

Wes

CaseyRyan

4:06 pm on Dec 17, 2004 (gmt 0)

10+ Year Member



Here is some code which does that. I also added a +10 and -10 because the add/subtract function (changeValue) is generic and can be reused.

<script language=javascript>
function changeValue(textObject,delta){
var myVal = parseInt(textObject.value);
if (myVal == NaN) {
myVal = 0;
} else {
myVal = myVal + delta;
}
/* check that it is not negetive */
if (myVal < 0) {
myVal = 0;
}
textObject.value = myVal;
return;
}
</script>
<form name="myform">
<input type=button value="-10" onclick="javascript:changeValue(document.myform.quantity,-10);return false;">
<input type=button value="-" onclick="javascript:changeValue(document.myform.quantity,-1);return false;">
<input type=text value=0 name="quantity" size=4>
<input type=button value="+" onclick="javascript:changeValue(document.myform.quantity,1);return false;">
<input type=button value="+10" onclick="javascript:changeValue(document.myform.quantity,10);return false;">
</form>

-=casey=-

wfernley

6:32 pm on Dec 17, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Casey.

Thanks for the reply, that script works great!

Thanks again for your help :)

Wes