views:

106

answers:

4

I am recently working in a project. There I need to convert language from English to Japanese by button click event. The text is in a div. Like this:

"<div id="sampletext"> here is the text </div>"
"<div id="normaltext"> here is the text </div>"

The text is come from database. How can I convert this text easily?

A: 

If you mean translating the text, you cannot do it easily. To get some idea of the best attempts that software can make at translating natural languages, go to Google Translate or Babelfish. It's not that good, but it's sometimes an intelligible starting point.

If you just mean setting the language attribute on an element, then assign a new language code to the lang property of the div element object.

document.getElementById("normaltext").lang = "en-US";

I don't know the language code for Japanese; possibly ja-ja.

Daniel Earwicker
I think with the one but last sentence the OP meant to say that the strings are coming from a database so I assume so will the translations.
borisCallens
But then where is the ID that says which string to look up? And why not generate the page with both strings already in the correct translation?
Daniel Earwicker
That would be faster (content doesn't need to be fetched), but with long articles could make the page way too heavy.
borisCallens
Also, this wouldn't scale verry well (maybe in the future they want Dutch, German, French etc..)
borisCallens
In that case I'd do a single query to get all translations and then put them in the page in a JS array so I could pick the right one without any further load on the server.
Daniel Earwicker
A: 
Mattias Akerman
+2  A: 

Assuming that you have both the English and the Japanese version in the database, you can do two things:

  1. Use AJAX to load the correct text from the database and replace the contents of the div. There are tons and tons of tutorials on the internet about AJAX content replacement.
  2. Put both languages on the website and hide one using CSS display:none. Then use some JavaScript to hide/display the correct div when a button is clicked.

The first is technically more complex but keeps your page size small. The second one is very easy to do, but your page size is larger because you need to send both languages.

If the div is small and there is only one or two of these on the page, I recommend number two, the CSS technique. If the div is large (i.e. a complete article) or there are many of them then use the first method.

Sander Marechal
A: 

Assuming your literals have an id in your database you could put that id as a class in your div. Then with jquery fetch the ID, send it to your Ajax back-end and fetch the translated one.

borisCallens