Quote:
|
Originally Posted by oreoT
I've been posting some questions mainly about fields lateley and i've gotten good respons.
But theres one more thing I need to learn how to do:
I need to have have two links that add and subtract 1 to the value of a text field.
I'm gonna need to do this many times so a function would be best.
This is what I have:
Script:
var fieldname;
function add(fieldname) {
document.forms[0].fieldname.value++ ;
}
Html:
<input type="text" name="ABC" value="0">
<a href="javascript:add(ABC)">plus</a>
But it just doesnt work.
|
You should give your text box an "id" attribute, so you can use document.getElementById() in the add() function:
Code:
function add(field)
{
field = document.getElementById(field);
Now you can get the field's value, but since it's a text box, the script will see the value as a string, not a number. That's why this line:
Code:
document.forms[0].fieldname.value++ ;
doesn't work in your original function. You need to use parseInt() to get an integer value from a string:
Code:
function add(field)
{
field = document.getElementById(field);
val = parseInt(field.value);
I'm not really sure why, but the ++ syntax isn't going to work, you need to use +=
Code:
function add(field)
{
field = document.getElementById(field);
val = parseInt(field.value);
val += 1;
Now that you've read the value, turned it into a number, and added one to it, you just need to set the field to the new value:
Code:
function add(field)
{
field = document.getElementById(field);
val = parseInt(field.value);
val += 1;
field.value = val;
}
And the HTML can be something like this:
HTML Code:
<input type="text" name="ABC" id="ABC" value="0">
<a href="#" onclick="add('ABC');">+</a>
<a href="#" onclick="subtract('ABC');">-</a>
Oh, and when passing "ABC" to the function add(), you need to use quotes around 'ABC' otherwise the script thinks you're passing it an object.