Click to See Complete Forum and Search --> : Disabling form elements


Nibinaear
October 24th, 2006, 07:58 AM
Ive got some javascript for disabling form elements like this:


<script language="Javascript">
<!--
function setState()
{
var maga=document.subscription.mag.value;

if(maga=="online" || maga=="free_online")
{
document.subscription.username.disabled=false;
document.subscription.password.disabled=false;
document.subscription.password2.disabled=false;
}
else
{
document.subscription.username.disabled=true;
document.subscription.password.disabled=true;
document.subscription.password2.disabled=true;
}
}

setState();
-->
</script>


It works but only when I run it as an onChange state for example. The setState() you see there is never run, why? Basically I need to disable or enable the username and password fields when a drop down with 4 options contains a certain state (online or both = enabled, free or none = disabled).

This is fine when someone changes the drop down because I have an onChange, but I need it to alter the state when the form is run. I've tried:

<form onOnload="setState();">

but that didn't work. I am unable to use the:

<body onLoad="setState();"

because that tag is contained within my header file and this function only needs to be available on one page which imports the header.

Eli Gassert
October 24th, 2006, 08:05 AM
google for an cross-platform instance of attachEvent or addEvent (they go by two names). Then, you can do (anywhere in your code, head, foot, first line, last line):


addEvent(document.body, load, function() { setState(); });

PeejAvery
October 24th, 2006, 08:17 AM
You can check Firefox's Error Console to debug better. Okay, do an improve then.

...form here and script below (without function)...
</form>
<script language="Javascript">
var maga=document.subscription.mag.value;

if(maga=="online" || maga=="free_online")
{
document.subscription.username.disabled=false;
document.subscription.password.disabled=false;
document.subscription.password2.disabled=false;
}
else
{
document.subscription.username.disabled=true;
document.subscription.password.disabled=true;
document.subscription.password2.disabled=true;
}
</script>

Nibinaear
October 24th, 2006, 09:07 AM
Perfect, why didn't I think of that. I added the javascript without the function to the bottom as Peejavery said.

PeejAvery
October 24th, 2006, 09:25 AM
Glad to be of help.