troubleshooting Question

Javascript function to change form fields

Avatar of highlawn
highlawnFlag for United Kingdom of Great Britain and Northern Ireland asked on
Scripting Languages
9 Comments1 Solution365 ViewsLast Modified:
Hi - I wonder if anyone can help with what is hopefully a simple javascript request - if such a thing exists!

What I want to do is to examine a pair of fields - lets call them F1 and F2 - both of which are select boxes and both of which can have the values of "Yes" and "No".

If F1 is set to "Yes" then F2 must be set to "No" and vice versa. Now, I could probably do this using the form name and form field names and so on via the onchange event, but it struck me that there must be some way of writing a generic script that would allow you to pass the relevant parameters and cause the setting of the companion field to be the opposite.

So, the script being called doesn't know the form name (or ID) and doesn't know the field names/ids and doesn't know the value pairs - these all being passed at onchange time.

Does anyone know how I pass the fields to the JS function? For example if I have:

<form name="form1">
  <select name="f1" OnChange="change_values(this)">
      <option value="Yes">Yes</option>
      <option value="No">No</option>
  <select name="f2" OnChange="change_values(this)">
      <option value="Yes">Yes</option>
      <option value="No">No</option>

And the javascript...

 <script type="text/javascript">
  function change_values(form_field)
  if (formfield.form.f1.value == "Yes"){
  formfield.form.f2.value = "No"
  formfield.form.f2.value = "Yes"

But I don't want to hard code F1 or F2 or "Yes" or "No" and my JS is pretty basic!

Many thanks
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 9 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 9 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros