abhinav singh abhinav singh - 4 months ago 17
HTML Question

How to modify the javascript code to receive input from the user?

I am struck with my language translation tool .
Here is the code that google translate API has .
I have to modify this code to receive input from the user in a text box and then identify the language it is typed in. Currently the code is picking up the values from id="sourceText" .
I need to put in a text box there to make it a simple dynamic tool . Please tell me what modifications should be made to add a text box and receive its input and detect the language ? Thanks...

<html>
<head>
<title>Translate API Example</title>
</head>
<body>
<div id="sourceText">Hello world</div>
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
</script>
<script>
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;

// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
</script>
</body>
</html>

Answer

Change

<div id="sourceText">Hello world</div>

to

<textarea id="sourceText">Hello World</textarea>

Also update this line:

var sourceText = escape(document.getElementById("sourceText").value);


   <html>
   <head>
   <title>Translate API Example</title>
   </head>
   <body>
  <textarea id="sourceText">Hello world</textarea>
  <input type="button" value="Translate" onclick="submit()" />
<div id="translation"></div>
<script>
  function translateText(response) { 
    document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
  }

 function submit() {
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  var sourceText = escape(document.getElementById("sourceText").innerHTML);
  var source = 'https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
  newScript.src = source;

  // When we add this script to the head, the request is sent off.
  document.getElementsByTagName('head')[0].appendChild(newScript);
 }
  </script>
  </body>
  </html>
Comments