Facebook Cookbook - Jay Goldman [105]
function getText(targetField){
var indexes = document.getElementById(targetField).getSelection();
var fullText = document.getElementById(targetField).getValue();
if(indexes.start == indexes.end){
// There's nothing selected so return the whole thing
return fullText;
}else{
// Substring out the part that's selected and return it
return fullText.substr(indexes.start,(indexes.end - indexes.start));
}
}
NOTE
You’ll note a call in there to getValue(), which you might not recognize. It’s a handy function provided by Facebook Platform that will figure out what type of object you’ve called it on and will then use the appropriate methods to retrieve and return the value of it. See Manipulating DOM Elements for more information.
Limiting the Length of Text Fields
Problem
I have a text field in my app, and I want to limit the number of characters someone can type into it.
Solution
You’re looking for a combination of getValue() and setValue(), a pair of getter/setters implemented by Facebook as a shortcut to manipulating the value of various object types. If your Canvas page is set up something like this:
then give this a shot:
function limitLength(targetField,maxLength){
var currentLength = targetField.getValue().length;
if( currentLength > maxLength){
targetField.setValue(targetField.getValue().substring(0, maxLength));
currentLength = maxLength;
}
document.getElementById('messageCount').setTextValue(currentLength + '/200
characters');
}
Discussion
There are lots of occasions in which you might need to do something like limit the length of a text field, so it’s always better to try to write functions like that as general-purpose utilities rather than one-time-use tools. That function could have been written as checkMessageField() without passing in the field or length, but then you’d also need checkProfileField() and checkDescriptionField(), etc. Since FBJS allows you to include external JavaScript files, do yourself a favor and put things like this into a utilities.js, which you can just include in pages where you need them (see Linking to External FBJS Files).
Creating Elements Dynamically
Problem
I want to dynamically create DOM objects and pop them into my page.
Solution
Use document.createElement(), the same way that you would in traditional JavaScript.
Discussion
This is one of the things that doesn’t change in FBJS, so your knowledge of off-Facebook JavaScript can be applied directly.
One special exception to note: document.createElement() can be used to create FBML elements, but it is currently limited to var newFlash = document.createElement('fb:swf'); Once you’ve created your object and attached it to the DOM (using a call such as appendChild()), you will not be able to move it around the DOM, and it will be rendered by the FBML parser into a standard