Forum Moderators: open

Message Too Old, No Replies

increment form field value

increment form field value

         

decbrad

9:49 am on Jun 14, 2007 (gmt 0)

10+ Year Member



Hi all... just a quick question! I have a standard form field that gets filled from a database when the page loads... all good so far! What I would like to do is allow the users to increment this value by adding a plus and minus each side.

Here's my hacked effort so far... ;o(

<script type="text/javascript">
function add() {
document.getElementById('input').value=document.getElementById('input').value + .1;
}

function subtract() {
document.getElementById('input').value=document.getElementById('input').value - .1;
}
</script>

<form>
Value:
<input type="button" onClick="subtract();" value="-" name="button">
<input type="text" name="input" value="18.3" id="input" size="5" maxlength="4">
<input type="button" onClick="add();" value="+" name="button2">
</form>

It seems to work when subtracting but not when adding? If anybody can point me in the right diection, or even to an online tutorial, i'd seriously appreciate it!

Thanks in advance

Decbrad

penders

11:07 am on Jun 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Because '+' is also used for string concatenation, and JS assumes that the contents of form fields are strings, things can at times not turn out as expected... If you tell JS that the .value is a number (ie. convert it with parseFloat()) then it should be OK...

document.getElementById('input').value = parseFloat(document.getElementById('input').value) + .1;

<edit>

Just noticed another (recent) related thread which may help...
[webmasterworld.com...]

decbrad

10:16 pm on Jun 14, 2007 (gmt 0)

10+ Year Member



Thanks a million Penders... that worked a treat;o)

rgds,
Decbrad