Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Disabling form controls conditionally 1

Status
Not open for further replies.

jwpward

Programmer
Sep 5, 2003
45
GB
Hi

Is there a way in javascript to disable certain controls on a form, according to some other data on the page?

E.g. A web page brings up a customers information which includes a 'gender' text field. The customer needs to check some radio buttons as part of the form, but if the gender attribute is 'male' only some of the radio buttons should be available. If the gender is 'female', other radio buttons are available when the page had loaded.

Sorry about the slightly ambiguous example. It's more of a hypothetical question.

Thanks a lot in advance

 
Yes - this can be done.

You can put an "onchange" (or onclick, onblur, etc, as appropriate) event handler onto any form element to fire a JS function when its value is changed.

Hope this helps,
Dan



[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Hi Dan

Thanks for your reply. How would you use the onchange event handler to disable a radio button? It would need to be done as soon as the page loaded, so the ability to check certain buttons is taken out of the users hands.

Hope this makes sense.

Cheers

 
Assuming this is a straight HTML page (i.e., not a JSP), you can create a function which checks the values of particular fields then disables certain other fields accordingly.

Then, in the BODY tag, add onload='myFunction();'. The updating/disabling will occur right away.

--Dave
 
Hi Dave

This should do the job perfectly. Once I've run the onload function how can I explicitly disable a radio button. Sorry, not sure of the syntax. Using my earlier example..

function myFunction(){
if(txtGender.value == "Male"){

r1. . .;//needs to be disabled
}
}

Thanks again
 
Hi

Ignore last post. I can just add:

r1.disabled = true;

Cheers

 
If r1 is a stand-alone button (i.e, there is only one button named r1:

Code:
r1.disabled = true;

...should do it.

If there are three buttons named r1 (for example)
Code:
for(var i=0; i<r1.length; i++)
 r1[i].disabled = true;

And if you only want the r1 with a id of 'hasAdamsApple' to be disabled (for example):
Code:
for(var i=0; i<r1.length; i++)
 if(r1[i].id == 'hasAdamsApple')
  r1[i].disabled = true;

'hope this helps.

--Dave
 
Thanks for all your help. Much appreciated.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top