Quick Javascript question...

MoobyTheGoldenCalf

Golden Member
Jul 26, 2001
1,146
0
76
I'm building a form and I need it so that if a user checks a certain checkbox, a few separate lines of text in various places of the form will change. And if they uncheck, the text will revert back to the way it was. Easiest way to do this?
 

NanoStuff

Banned
Mar 23, 2006
2,981
1
0
document.<form name>.<checkbox name>.checked returns true/false, so use this to determine IF checked. Or you can use getElementsByTagName[<index number of checkbox>].checked, or you can use getElementById[<ID of checkbox>].checked

Using getElementById you can then get the element whose text is to be changed and use .innerHTML on it to change the text. innerText should also work to capture the text node itself if you want to access the parent directly while there are other tags within that element.

You might also want to store the retrieved element in a variable and just access it with variable.checked, which would improve performance, though probably insignificantly, but if you're going to refer to that element several times it will definitely shorten the code.

Of course, you need to attach a 'click' event handler on the checkbox to execute the code. How you do this depends on the browser you're using, so you should probably look up event handlers in detail for your browser. The best thing to do is to use a library such as prototype or jQuery that handles the element checking for you and assigns according to what is available on the client. IE uses attachEvent(), W3C compliant browsers use addEventHandler(). Good news is both browsers simply accept .<event>, such as .******(), but this approach is being considered deprecated, so it's best to stop using it just to stay in gear.

[edit] the stars were meant to show on-click without the '-', it seems the forum is taking some precautions to avoid XSS attacks :)