In this article I will illustrate how to convert text from one language to another in JavaScript.It can be achieved using Google API’s. There are many versions of API’s released.
here in this example i will use “jsapi” by referring following link in my web page.
<script type="text/javascript" src="https://www.google.com/jsapi">
else one can download java script file from the above link and reference it in the page.
Ex: Suppose we have two textboxes , one for entering English text and the other to display translated text. Enter text in English and press tab , converted text will appear in another textbox.
ASPX Code :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex.aspx.cs" Inherits="Ex" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("language", "1");
function myfunction() {
var filed = 'txtEng'
var strEngName = document.getElementById(filed).value;
var strEngArray = new Array();
strEngArray = strEngName.split(" ");
var str = '';
if (document.getElementById('txtEng').value.length == 0) {
document.getElementById('txtTel').value = '';
}
document.getElementById('txtEng').value = document.getElementById('txtEng').value.replace(/^\s+|\s+$/g, '');
for (i = 0; i < strEngArray.length; i++)
{
var temp = strEngArray[i];
google.language.transliterate([strEngArray[i]], "en", "te", function (result)
{
if (!result.error) {
var container = document.getElementById('txtTel');
if (result.transliterations && result.transliterations.length > 0 && result.transliterations[0].transliteratedWords.length > 0) {
container.value = result.transliterations[0].transliteratedWords[0];
str = str + ' ' + container.value;
}
document.getElementById('txtTel').value = str;
}
}
);
}
}
google.setOnLoadCallback(myfunction);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tbody>
<tr>
<td>
Enter the Name(English)
</td>
<td>
<input id="txtEng" style="background-color:pink;width:380px; height:30px;font-size:18px;font-weight:bold" onblur="javascript:myfunction();" />
</td>
</tr>
<tr>
<td>Translated Text: </td>
<td>
<input id="txtTel" style="background-color:yellow;width:380px; height:50px;font-size:18px;font-weight:bold" />
</td>
</tr>
</tbody>
</table>
<br>
</div>
</form>
</body>
</html>
OUTPUT :