Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.
Related
I am calling a SOAP service in my Javascript code, and the response of this service is correct but strings returned does not show letters with accents. So, I have a problem with encoding charset and I am trying the following actions:
1) I ensure that the HTTP response returning string data has the correct charset defined. So, I have checked with https://validator.w3.org/i18n-checker/ that the encoding charset of the URI that I am calling is "utf-8".
2) I have defined charset in the head section of html:
<meta charset='utf-8' content-type="text/xml;charset=UTF-8"/>
3) Also, I call this service with a function in module.js, I have also defined
<script src="node_modules/my_module.js" charset="utf-8"></script>
All three with the same wrong result.
I added an image with the some examples:
image with result strings, where in green square have to say 'Sant Martí de Tous', in red 'Moianès', in blue 'Santa Bàrbara', 'Montsià', in orange 'Torroella de Montgrí', etc
This is a minimum sample code to call SOAP service with tinysoap library:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' content-type="text/xml; charset=utf-8"/>
<title>Test Charset Encoding</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="node_modules/tinysoap/tinysoap-browser-min.js"></script>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
var tinySoap=this.tinysoap;
require(["esri/Map"], function(Map) {
var inputCtrl = document.getElementById("inputString"); // gironès
var outputCtrl = document.getElementById("outputString");
inputCtrl.onchange = function() {
var userTxtValue = inputCtrl.value;
var args = {nom: userTxtValue};
//console.log("[INPUT] : ",args);
//outputCtrl.innerHTML = "<br><b>Input ... </b>" + userTxtValue +"<br>";
tinySoap.createClient(url, function(err, client){
client.localitzaToponim(args, function(err, result) {
var data = result['item'];
//console.log("[OUTPUT] : ",data);
//outputCtrl.innerHTML += "<b>Output ... </b>";
//data.forEach(element => {
// outputCtrl.innerHTML += "<br> "+ element.Nom;
//});
});
});
}
});
</script>
</head>
<body>
Look for place or address ...
<input id="inputString" size="50" value=""><br>
<span id="outputString"></span>
</body>
</html>
This is the result of this process for 'gironès' as input string
There is the error: "Refused to set unsafe header", but I can not see where to set header parameters to connection.
I am still working in that problem: I have checked that strings are encoded as UTF16 with this library: https://github.com/polygonplanet/encoding.js/
using Encoding.detect(string), but Encoding.convert(string,'utf8','utf16') does not work for me, neither Encoding.convert(string,'latin1','utf16'), etc
What is the right way to define the encoding charset? Thank you
I'm new to using JavaScript so please excuse my bad terminology.
I have a jQuery that is calling an API for a dictionary web service, the whole function works as it should (returning all of the definitions, authors, etc..).
But my problem is that the returned data from the API is coming back in one big block of text and not in a neat format with line spacing between each definition.
If I just search for the URL in a web browser, I get a json response with tidy definitions and spacing.
Here is my search in the service to the API and the data returned.
http://epvpimg.com/MkdEg
Here is the search just using the URL from my code through a web browser (how I think it should look when returned in my web service)
http://epvpimg.com/IWLJf
Has anybody ever seen this problem before or know why, from my code, it is doing so!
Any help would be much appreciated!
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" +word+ "?callback=?", function(json) {
if (json !== "No definition has been found."){
var reply = JSON.stringify(json,null,"\t");
var n = reply.indexOf("meanings");
var sub = reply.substring(n+8,reply.length);
var subn = sub.indexOf("]");
sub = sub.substring(0,subn);
$('#definition').html('<h2 class="loading">We found you a definition!</h2><h3>'+sub+'</h3>');
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
And the HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<input type="text" placeholder="Enter a word..." id="term" />
<button id="search">Define!</button>
<section id="definition">
</section>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
You're providing a third argument to JSON.stringify, which pretty-prints the result. So sub should have the line breaks you want. The problem is that you're putting it in an HTML document, and HTML automatically merges lines. You can prevent this by using the <pre> tag:
$('#definition').html('<h2 class="loading">We found you a definition!</h2><br><pre>'+sub+'</pre>');
I have a very internationalised website, however I need to produce a pop-up specifically for our UK customers.
What I require is:
On page load: Is the user from the UK?
If yes then show div.
Else
Div remains hidden.
You can do this using freegeoip.
Since you mentioned that you want to use plain JavaScript (not jQuery), you should use JSONP to get the country:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>UK localisation</title>
</head>
<body>
<div id="myDiv" style="display:none">
<h1>Kittens</h1>
</div>
<script>
function toggleDiv(content) {
console.log(content.country_code);
if(content.country_code === 'GB') //Or GBR, or UK, I'm not sure.
{
document.getElementById('myDiv').style.display = "inline";
}
else
{
alert("You are not from UK, you are from " + content.country_code);
document.getElementById('myDiv').style.display = "none";
}
}
window.onload = function()
{
// create script element
var script = document.createElement('script');
// passing src with callback name
script.src = 'http://freegeoip.net/json/?callback=toggleDiv';
// insert script to document and load content
document.body.appendChild(script);
}
</script>
</body>
</html>
Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.
I am having problem with this error:
'undefined' is null or not an object'
Can you please have a look and let me know. In my coding, I want to have simple DOM JavaScript code
<!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" />
<title>Untitled Document</title>
</head>
<script>
init();
function init()
{
getElementByTabIndex("4", "submit")[0].addEventListener("click", Verify, false);
}
function Verify() {
alert('done');
// all verification code will be here...
}
function getElementByTabIndex(index, type, node)
{
if (!node)
{
node = document.getElementsByTagName('body')[0];
}
var a = [];
els = node.getElementsByTagName('*');
for (var i = 0, j = els.length; i < j; i++)
{
if (els[i].tabIndex == index && els[i].type == type)
{
a.push(els[i]);
}
}
return a;
}
</script>
<body>
<input type="email" id="email" /><input type="password" id="pass" /> <label class="Login" for="login"><input value="Log In" tabindex="4" type="submit" id="login"></label>
</body>
</html>
You have to move you code at bottom or call init() after body is loaded.
Reason: you are trying to get elements even before they exists.
Eg :
<head>
<script>
var elm= document.getElementById('id');
//this will be always undefied, as trying to read element even before they exist
</script>
</head>
<body>
<div id='foo'></div>
<script>
var elm= document.getElementById('id');
//this wont be undefined
</script>
</body>
You call:
if (!node) {
node = document.getElementsByTagName('body')[0];
}
But your script runs before the DOM has finished loading, and so the body tag does not exist.
So node is undefined, and when you attempt the following, you get your error:
node.getElementsByTagName('*');
Run init() on document load, instead of immediately.
PS. jsfiddle and Firebug allowed me to debug this very quickly.
'body' isn't available to javascript at the time you are trying to call init().
call your init method when the dom has finished loading, like so:
window.onload = function (){
init();
}
note that in order to make this work across browsers (if you plan on using it outside your planned Safari extention) you will have to do some extra work. more info: http://www.javascriptkit.com/dhtmltutors/domready.shtml