Reputation: 311
I need to set the text of a HTML label with various language translations. I know how to do it when i know the ID of the label, but i want to make a general Javascript function which does not require the id. In this order, I need some thing like this:
HTML:
<label> <script> translating_function("hello"); </script> </label>
JAVASCRIPT:
function translating_function(string) {
//finding the translation (for example translated_text)
returning translated_text
}
The return of the translating_function function should be set as the text of the label. Does any one have any idea how to do it. Thank you very much.
Upvotes: 1
Views: 1005
Reputation: 2324
var voc = [
{
"AR":"أهلا",
"ES":"¡Hola",
"EN":"hello"
},
{
"AR":"مرحبا",
"ES":"bienvenida",
"EN":"welcome"
},
{
"AR":"و",
"ES":"y",
"EN":"and"
},
{
"AR":"في اللغة العربية",
"ES":"a España",
"EN":"to English"
}
];
function translate(ele,lng){
for(var i=0;i<voc.length;i++){
for(var k in voc[i]){
if(voc[i][k] == ele.innerText.trim()){
ele.innerText = voc[i][lng];
break;
}
}
}
}
function translateTo(lng){
var trc = document.getElementsByClassName("translatable");
for(var i=0;i<trc.length;i++){
translate(trc[i],lng);
}
}
//add this function to any event button.click,select.change or on load
//translateTo("AR");
<p>
<span class='translatable'>hello</span>
<span class='translatable'>and</span>
<span class='translatable'>welcome</span>
<span class='translatable'>to English</span> :)
</p>
<select onchange='translateTo(this.value)'>
<option value='EN'>English</option>
<option value='AR'>Arabic</option>
<option value='ES'>Espain</option>
</select>
Upvotes: 1
Reputation: 1120
<script>
function translating_function(str) {
return 'translating: ' + str;
}
</script>
<label> <script> document.write(translating_function("hello")); </script> </label>
Upvotes: 0