Just call the function below with the id values for the source field and the target field.
var XMLHttpRequestObject = false;
//check browser
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function translate(sourceID, targetID) {
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var sourceFld = document.getElementById(sourceID);
var targetFld = document.getElementById(targetID);
var sourceText = sourceFld.value;
var tmpURL = "https://www.googleapis.com/language/translate/v2?q=" + sourceText + "&target=es&source=en&key=" + apikey + "";
if (sourceText!="") {
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET", tmpURL );
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
//parse into JSON
var json = JSON.parse(XMLHttpRequestObject.responseText);
//raw return value
var translatedText = json.data.translations[0].translatedText;
//cleanup
translatedText =translatedText.replace(/"/g, '"'); //replaces ALL " with "
//output
targetFld.value = translatedText;
}
}
XMLHttpRequestObject.send(null);
}
}
}