Question

I'm a bit stumped by the Facebook implementation of Javascript. I want to set up a listener on a checkbox so that when checked, it changes the class of an element I can get by ID.

I've been using the test console and have tried various permutations. Javascript is NOT my first language, nor my second, third... COuld anyone help me by translating my pseudocode?

<input class="one" type="checkbox" onclick="setcolor(this.checkedornot)">
    function setcolor(checkedornot){
        if checkedornot == true {set p.one to p.one.GREEN}
        if checkedornot == false {set p.one to p.one.RED}
    }

Obviously this is not javascript, but that is how I can best explain the functionality I need. In my short tests, FBJS doesn't even seem to register onClick events. Thanks!

Was it helpful?

Solution

FBJS has its own getters and setters. Getting "checked" and setting/removing classes are different. And, you would have to remove the "red" class if you are adding the "green" class, and visa versa. Or, if you just want to overwrite all the classes of the element, you can use the setClassName(class) method instead, I'm going to use the add/remove class methods in my answer since it is less destructive.

FBJS Docs: Manipulating Objects

For the onclick event, I think you're supposed to use the addEventListener if onclick doesn't work. Events in FBJS

Instead of this.checked, FBJS uses getChecked. So when you add the event listener (for "click"), add a "this.getChecked()" for the arg.

setColor(this.getChecked());

And for the function:

function setColor (isChecked) {
    var p = document.getElementById(ID-OF-P);
    if (isChecked) {
        p.removeClassName("red");
        p.addClassName("green");
    } else {
        p.removeClassName("green");
        p.addClassName("red");
    }
}

I am a JS newb too though. I think this is right.

OTHER TIPS

For the onclick event you need to use...

this.checked

Then your function will look like this:

var setColor = function(isChecked) {
    var myElement = document.getElementById("one");
    if (isChecked) {
        myElement.className = "myGreenClass";
    } else {
        myElement.className = "myRedClass";
    }
};

kmiyashiro is mostly right except for the getters and setters for the class name it should be

  if (isChecked) {
    p.setClassName("green");
} else {
    p.setClassName("red");
}

Since its just a set meothod and there are no remove methods, you don't need to worry about removiing the class name, it will just get overwritten.

check out this list for more getters and setters http://wiki.developers.facebook.com/index.php/FBJS#Manipulating_Objects

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top