Changing values of hidden fields from checkboxes

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
spartan7
Forum Commoner
Posts: 29
Joined: Sun Jun 19, 2005 12:09 am

Changing values of hidden fields from checkboxes

Post 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
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post 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. :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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;
}
Post Reply