April_Nara
April_Nara

Reputation: 1046

JavaScript 'function undefined' error working with jsfiddle

I'm trying just to understand an error completely because sometimes I can get around it and other times I can't. I've tried just writing a function:

function toggleButton() {
}

But I get the same error. This is the .js sample.

var checkBox = document.getElementById("chkMyBox"); 

 checkBox.onclick = function toggleButton(e, obj1) 
 {    
var btnElement = document.getElementById("btnMyButton");
    if(btnElement != null) {
        alert("Element not null");
    if(e.target.checked && obj1 != null) {
        alert("Checking check " + obj1.checked);
         if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
            btnElement.getAttribute('disabled') = false;
        } else {
                btnElement.getAttribute('disabled') = true;
        } 
    }
  }  
}

Here's the html:

<form id="frmCheckBox">
   <input type="checkbox" id="chkMyBox" />    
   <button id="btnMyButton" disabled>I'm a Button</button>
</form>

http://jsfiddle.net/Arandolph0/h8Re6/3/

Upvotes: 0

Views: 402

Answers (3)

user1693593
user1693593

Reputation:

Change this line which uses name:

<input type="checkbox" name="chkMyBox" />    

into using id instead:

<input type="checkbox" id="chkMyBox" />    

Alternatively you could use:

var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array

or

var element = document.getElementsByName('chkMyBox')[0];

Update (as OP changed the code from the original question):

function toggleButton(e, obj1) 

This won't work as there is only a single argument given to the callback function (e). Use e.target to get the element.

Upvotes: 5

Justin Niessner
Justin Niessner

Reputation: 245399

You have several problems here.

1) You try to get the button by using getElementById but your element has no id. The easiest fix is to fix your markup.

<input type="checkbox" name="chkMyBox" id="chkMyBox" />

2) Your event handler takes two parameters. When attaching the handler via the DOM, only the event gets passed to your handler. Therefore obj1 will always be undefined. You need to get the checkbox element from the e parameter.

checkBox.onclick = function(e) {
    var obj1 = e.target;
    // rest of handler
}

3) You shouldn't use getAttribute to check for the element being disabled/enabled. It will give you the text value of the attribute which is an empty string. Instead, use the boolean property that the DOM gives you:

// toggle the disabled attribute
obj1.disabled = !obj1.disabled;

Upvotes: 1

Bill Criswell
Bill Criswell

Reputation: 32921

You're trying to get an element by its name. You'd have to do:

var checkBox = document.getElementsByName('chkMyBox')[0];

Or, if you prefer by id. Just add id="chkMyBox" to your checkbox input.

Upvotes: 1

Related Questions