Search code examples
language-translationgoogle-translator-toolkit

How can I use Google Translate for translating values in a website form field (text box, text area)?


I want to translate my website using Google Translate. I used the code below.

<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
    new google.translate.TranslateElement({
        pageLanguage: 'en'
    }, 'google_translate_element');
}
</script><script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

It is working fine with text of the website, but does not translate the text box, text area's text. Is there a solution?


Solution

  • You could iterate through the elements in your page and make individual ajax calls to Google Translate API to translate them one by one and them replace the textbox/textarea values.

    Using jQuery, you can iterate through your textbox, textareas and everything else you want to. The code should be something like:

    $('input:text').each(function(index) {
    
        var elementId = $(this).attr("id"); 
    
        //Call the Google API
        $.ajax({
            type : "GET",
            url : "https://ajax.googleapis.com/ajax/services/language/translate",
            dataType : 'jsonp',
            cache: false,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            data : "v=1.0&q="+$("#"+elementId).val()+"&langpair=en|es",
            success : function(iData){
                //update the value
                $("#"+elementId).val(iData["responseData"]["translatedText"]);      
            },
            error:function (xhr, ajaxOptions, thrownError){ }
        });
    });
    

    As you can see, the parameter &langpair=en|es asks to translate from English to Spanish.

    Just remember that one call will be made for each <input type="text".../>, so you might want to add some kind of validation to filter useless calls! You might also want to validate Google's answer.

    Here is a link in order to understand the kind of response Google will send you: http://code.google.com/apis/language/translate/v1/using_rest_translate.html

    EDIT: Since free use of Google's API will be shut down on 2011-12-01, you could use Apertium. The call and response is almost the same: http://api.apertium.org/json/translate?q=hello%20world&langpair=en|es