e-beth
e-beth

Reputation: 77

Populate text field when select radio button

I have an HTML form where I am trying to get a text field to display certain text when I select one of the radio buttons. So far, I have it to where if I click the button it will display the proper text in the text field. My goal is to eliminate the "Click" button and have the text field display the text immediately when I select a radio button. How can I do this in Javascript?

I know that textfields have an 'OnKeyUp' event, but I can't seem to figure out if a radio button has some sort of similar thing that would allow me to determine when one is selected. I've tried OnChange and OnFocus events, but maybe I'm doing it wrong because I can't get those to work. Any and all suggestions are much appreciated.

This is what I have so far:

<HTML>
  <HEAD>
    <TITLE>Test Input</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
      function testResults (form) {
      var TestVar1 = form.input[0].checked;
      var TestVar2 = form.input[1].checked;
        if (TestVar1 == true) {
          form.textbox.value = "red";
        } else if (TestVar2 == true){
          form.textbox.value = "blue";
        } else if (TestVar1 == false && TestVar2 == false) {
          form.textbox.value = "";
        }
      }
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Color: <BR>
  <INPUT TYPE="radio" NAME="input" VALUE="red">red<P>
  <INPUT TYPE="radio" NAME="input" VALUE="blue">blue<P>
  <INPUT TYPE="button" NAME="button" VALUE="Click" onClick="testResults(this.form)">
  <P>Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div><p>

</FORM>
</BODY>
</HTML>

Upvotes: 1

Views: 6749

Answers (1)

userDEV
userDEV

Reputation: 535

Change the following two lines of code adding the onchange event:

TYPE="radio" NAME="input" VALUE="red"  onchange="testResults(this.form)
TYPE="radio" NAME="input" VALUE="blue" onchange="testResults(this.form)

If that doesn't work, it may be your browser. document.getElementByID is an object except by all browsers

Upvotes: 2

Related Questions