user3870923
user3870923

Reputation: 1

Checkbox inserts text into textarea with Javascript

I am trying to do something really simple using only Javascript (not JQuery). Basically, I want to use a checkbox to toggle the text in a textarea. So if the checkbox is unchecked I want it to say "Hello" in the textarea. If the checkbox is checked, the textarea should say "Goodbye". I'm just getting started with Javascript, so any help would be appreciated. Thanks

Here is the code:

var myswitch = document.getElementsByTagName("myonoffswitch");
var mytextarea= document.getElementsByTagName("mytextarea");
myswitch.onchange = function(){
      if(this.checked){
        mytextarea.value = "Hello"
      }else{
        mytextarea.value = "Goodbye"
    }
}

Upvotes: 0

Views: 1808

Answers (4)

Devendra Soni
Devendra Soni

Reputation: 1934

Just try replacing getElementsByTagName in your code with getElementById this will solve your problem.

Upvotes: 0

RobG
RobG

Reputation: 147563

If your controls are in a form, you can do something really simple like:

<form>
  <textarea name="ta"></textarea>
  <input type="checkbox" onclick="
    this.form.ta.value = this.checked? 'Hello':'Goodbye';
  ">
</form>

Note that using the change event with a checkbox means that in some browsers, the event won't be dispatched until the checkbox loses focus, so better to use the click event.

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25892

I've tried something. This should work for you

HTML

<input type="checkbox" id="myonoffswitch">Switch</input>
<textarea id="mytextarea" cols="30" rows="10"></textarea>

Javascript

function fillText() {
        var myswitch = document.getElementById("myonoffswitch");
        var mytextarea= document.getElementById("mytextarea");
        myswitch.onchange = function(){
            if(this.checked){
                mytextarea.value = "Hello"
            }else{
                mytextarea.value = "Goodbye"
            }
        }
    }
    window.onload = fillText;

Upvotes: 0

jasonscript
jasonscript

Reputation: 6178

You should be using document.getElementById instead of getElementsByTagName

I can't tell from your code snippet if you've wrapped your code in an onload function. This is required in situations where your DOM elements are not loaded in the HTML at the time your javascript is running

Here's an example

window.onload = function () {
    var myswitch = document.getElementById("myonoffswitch");
    var mytextarea = document.getElementById("mytextarea");
    myswitch.onchange = function () {
        if (this.checked) {
            mytextarea.value = "Hello";
        } else {
            mytextarea.value = "Goodbye";
        }
    }
    //code here
}

And a fiddle is available here: http://jsfiddle.net/C4jVG/

Upvotes: 0

Related Questions