views:

150

answers:

1

Hello,

I've used "Google AJAX Transliteration API" and it's going well with me.

http://code.google.com/apis/ajaxlanguage/documentation/referenceTransliteration.html

Currently I've a project that I need all input fields in every page (input & textarea tags) to be transliteratable, while these input fields differs from page to page (dynamic). As I know, I've to call makeTransliteratable(elementIds, opt_options) method in the API call to define which input fields to make transliteratable, and in my case here I can't predefine those fields manually. Is there a way to achieve this?

Thanks in advance

A: 

Rephrasing what you are asking for: you would like to collect together all the inputs on the page which match a certain criteria, and then pass them into an api.

A quick look at the API reference says that makeTransliteratable will accept an array of id strings or an array of elements. Since we don't know the ids of the elements before hand, we shall pass an array of elements.

So, how to get the array of elements?

I'll show you two ways: a hard way and an easy way.

First, to get all of the text areas, we can do that using the document.getElementsByTagName API:

var textareas = document.getElementsByTagName("textarea");

Getting the list of inputs is slightly harder, since we don't want to include checkboxes, radio buttons etc. We can distinguish them by their type attribute, so lets write a quick function to make that distinction:

function selectElementsWithTypeAttribute(elements, type)
{
    var results = [];
    for (var i = 0; i < elements.length; i++)
    {
        if (elements[i].getAttribute("type") == type)
        {
            results.push(elements[i]);
        }
    }
    return results;
}

Now we can use this function to get the inputs, like this:

var inputs = document.getElementsByTagName("input")
var textInputs = selectElementsWithTypeAttribute(textInputs, "text");

Now that we have references to all of the text boxes, we can concatenate them into one array, and pass that to the api:

var allTextBoxes = [].concat(textareas).concat(textInputs);
makeTransliteratable(allTextBoxes, /* options here */);

So, this should all work, but we can make it easier with judicious use of library methods. If you were to download jQuery (google it), then you could write this more compact code instead:

var allTextBoxes = $("input[type='text'], textarea").toArray();
makeTransliteratable(allTextBoxes, /* options here */);

This uses a CSS selector to find all of the inputs with a type attribute of "text", and all textareas. There is a handy toArray method which puts all of the inputs into an array, ready to pass to makeTransliteratable.

I hope this helped, Douglas

Douglas