Page 1 of 1

Changing values of hidden fields from checkboxes

Posted: Wed Jul 05, 2006 4:09 pm
by spartan7
I have a checkbox and hidden field within a form :

Code: Select all

<input name="checkbox1" id="checkbox1" type="checkbox" value="abc" onClick="document.forms[0].hidden1.value = '1'>

<input name="hidden1" id="hidden1" type="hidden" value="0">
So, basically I'm changing the value of the hidden form from the checkbox onClick...Which is fine...But I also want when you click the checkbox again (to untick it) the hidden field reverts back to it's old value.

So I want if you click the checkbox first to tick it, the hidden1 value is put to 1. Then if you click that same checkbox again to untick it, I want the hidden1 value changed back to 0.

How do I do it?

Thanks

Posted: Wed Jul 05, 2006 4:22 pm
by JellyFish
I'm not much of a javascript guy, but maybe I can help with the logic in this.

What I would do is make a JS function that checks hidden1's value. For example:

Code: Select all

function checkhidden1value () {
      if (document.forms[0].hidden1.value == 1) {
            document.forms[0].hidden1.value = 0;
      } else if (document.forms[0].hidden1.value == 0) {
            document.forms[0].hidden1.value = 1;
      }
}
And then I'll place this function in the onClick event.

Hopefully this helps. :)

Posted: Wed Jul 05, 2006 4:43 pm
by feyd
I'd basically do what EasyGoing has said but write the function a little differently.

Code: Select all

function toggle(elementRef)
{
  var element = document.getElementById ? document.getElementById(elementRef);
  if (!element)
  {
    element = document.forms[0].element[elementRef];
  }

  if (!element)
  {
    return false;
  }

  element.value = (element.value == '0' ? '1' : '0');
  return true;
}