internationalization with jQuery - javascript

I'm trying to make a simple internationalization by replacing strings of text and I have developed the next code for it:
//INTERNACIONALIZACIÓN
$(function(){
arrayCadenas = $(".texts").text(); // make an array of strings to translate
var es_ES = ["Federación de reinserción1", "NOSOTROS", "QUIENES SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED INCORPORA", "APRENDIZAJE", "CONTACTO"];
var eu_EU = ["Federación de reinserción2", "GUK", "NORK GARA", "ZER EGIN", "PROIEKTUAK", "SGU-UPD SARTU II", "RED INCORPORA", "APRENDIZAJE", "KONTAKTUA"];
var en_EN = ["Federación de reinserción3", "NOSOTROS", "QUIENES SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED INCORPORA", "APRENDIZAJE", "CONTACTO"];
languages = [es_ES, eu_EU, en_EN];
$(".lang").each(function(i, lis){
$(this).on("click", function(e){
e.stopPropagation;
select = languages[i];
console.log(arrayCadenas);
console.log(languages[i]);
arrayCadenas.each(function(j, cadena){
cadena.text(languages[i][j]);
});
});
});
});
When I click on a flag, in console I got this:
[17:53:04.223] TypeError: arrayCadenas.each is not a function # file:///var/www/TRABAJOS/SARTUWEB/%2806-08-2013%29%20sartutheme7/index.html:253
[17:53:04.222] Federación de reinserciónNOSOTROSQUIENES SOMOSQUE HACEMOSPROYECTOSSGU-UPD SARTU IIRED INCORPORAAPRENDIZAJECONTACTO
[17:53:04.222] ["Federaci\xF3n de reinserci\xF3n3", "NOSOTROS", "QUIENES SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED INCORPORA", "APRENDIZAJE", "CONTACTO"]
Thanks for your help

//...
arrayCadenas = $(".texts");
//...
console.log(arrayCadenas.text());
//...
You are reading the inner text which does not have an each function. Read the objects instead.

Thanks for your answer Lajos Arpad. i was thinking about it and finally I solved it.
In the second each, where it says:
arrayCadenas.each(function(j, cadena){
cadena.text(languages[i][j]);
});
I replace "cadena" by "$(this)", so the final code looks like this:
arrayCadenas.each(function(j, cadena){
$(this).text(languages[i][j]);
});
As a final comment, you can replace "$(this)" by "$(cadena)", bacause both of them references to the current item.
Thanks again.

Related

How to apply json content for html attribute

I am trying to add json object for html arrtibute content but not working.I have tried many ways but I do not know how to set that.if any one know about that please help to resolve this issue.
javascript:
var validatorValue='{
"picker":{
"allow":
{
"message": "Content loram ipsom"
},
"past":
{
"message": "lorem issom"
}
}
}' ;
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html("<div input="true" validator='+validatorValue+' date-restrict='+daterestrictValue+' my-input='+myinputValue+'></div>");
The main issue with your code (aside from line-breaks in string literals) it the mis-matched quotes in the HTML string you build. However, even after correcting those you will have issues placing serialised JSON within attributes as it too contains double quotes which will break the HTML syntax.
Also note that you're creating non-standard attributes in the HTML you create which may cause unexpected issues in your UI and JS.
An alternative way to approach this is to work with the values as objects (instead of strings). You can use jQuery to set the data of the element using those objects, like this:
var validatorValue = { "picker": { "allow": { "message": "Content loram ipsom" }, "past": { "message": "lorem issom" } } }
var daterestrictValue = { 'range': { 'start': '2019-10-30', 'end': '2019-12-30' } }
var myinputValue = { 'date': 'tomorrow' };
var $newDiv = $('<div data-input="true">Click me</div>').appendTo('#mydiv');
$newDiv.data({
"validator": validatorValue,
"date-restrict": daterestrictValue,
"my-input": myinputValue
});
// for testing
$('#mydiv div').on('click', function() {
console.log($(this).data('validator'));
console.log($(this).data('date-restrict'));
console.log($(this).data('my-input'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
this code save object in html element.
good luck
var validatorValue="{ 'picker':{'allow':{'message': 'Content loram ipsom'},'past':{'message': 'lorem issom'}}}";
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html(`
<div input='true' validator="${validatorValue}" date-restrict="${daterestrictValue}" my-input="${myinputValue}">ggg</div>`);

How to handle a large number of replaces?

I would like to know if there is a better way to handle a large number of jquery/javascript replaces. This is what my code currently looks like and I will be adding more words/phrases to it. I am wondering if I should be doing some sort of loop with the words in an array or an object? Or should the words maybe even be kept in a different file?
input = input.replace(/\band\b/g, "&")
//COMMON ABREVIATIONS
.replace(/\bwith\b/g, "w/")
.replace(/\bwithout\b/g, "w/o")
.replace(/\bpeople\b/g, "ppl")
.replace(/\bbecause\b/g, "b/c")
.replace(/\bestablished\b/g, "est.")
.replace(/\bstreet\b/gi, "St.")
.replace(/\bavenue\b/gi, "Ave.")
.replace(/\bparkway\b/gi, "Pkwy.")
.replace(/\blane\b/gi, "Ln.")
.replace(/\bboulevard\b/gi, "Blvd.")
.replace(/\bassociates\b/gi, "Assoc.")
.replace(/\bretweet\b/gi, "RT")
.replace(/\bapartment\b/gi, "Apt.")
.replace(/\bdirect message\b/gi, "DM")
.replace(/\bphoto credit\b/, "PC")
.replace(/\bphoto cred\b/, "PC");
I've found something, but unfortunately it doesn't catch phrases with two words. It's something wrong with the RegEx, I bet.
var input = {
'band': "&",
'with': "w/",
'without': "w/o",
'people': "ppl",
'because': "b/c",
'established': "est.",
'street': "St.",
'avenue': "Ave.",
'parkway': "Pkwy.",
'lane': "Ln.",
'boulevard': "Blvd.",
'associates': "Assoc.",
'retweet': "RT",
'apartment': "Apt.",
'direct message': "DM",
'photo credit': "PC",
'photo cred': "PC"
};
console.log('band with'.replace(/\w+/gi, match => input[match]));

select ng-options not updating ng-model in AngularJS with ajax

I have a simple question and I really dont know what am I missing in my logic.
In this Fiddle is working fine (not using ajax/timeout) but I want to understand and also fix why the following behavior is not happening when I apply the same logic with a timeout/ajax !!
Here is my simple sample: JS FIDDLE
HTML:
<body data-ng-app="appMain">
<div ng-controller="SearchController">
<input type="text" ng-model="SearchTerm" />
<input type="button" value="Submit Search" ng-click="QuerySuggestions()" />
<select ng-show="ShowSuggestion" name="cmbSelectedSuggestion" ng-model="SelectedSuggestion" ng-options="text as suggestion.Detail for suggestion in SuggestionList" ng-change="WhoIsSelected(suggestion)">
</select>
</div>
</body>
AngularJS:
angular.module('appMain',[])
.controller('SearchController',function($scope, $http, $timeout){
$scope.SearchTerm = '';
$scope.ShowSuggestion = false;
$scope.SuggestionList = [];
$scope.SelectedSuggestion = null;
$scope.QuerySuggestions = function()
{
//Simulating an AJAX that my response happens 2s afterwards
$timeout(function(){
var oJSON = {"List": [
{
"Id": 1,
"Type": "State",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - State, Brazil"
}
,
{
"Id": 1,
"Type": "City",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - City, Rio de Janeiro, Brazil"
}]};
$scope.SuggestionList = oJSON.List
$scope.ShowSuggestion = true;
}, 2000);
}
$scope.WhoIsSelected = function($option){
$scope.WhoIsSelectedFirstApproach();
$scope.WhoIsSelectedSecondApproach($option);
}
$scope.WhoIsSelectedFirstApproach = function(){
console.log($scope.SelectedSuggestion); //why undefined !?!?!
}
$scope.WhoIsSelectedSecondApproach = function($option){
console.log($option) //why undefined ?!?!?
}
})
In your ng-options, it should be suggestion.Detail as text instead of text as suggestion.Detail.
Well, after a bigger search I manage to solve and also understand my mistakes.
First, Due to my T-SQL background I was unterstanding that "text" was an alias for sugestion.Detail field in the expression text as suggestion.Detail for suggestion in SuggestionList but thats not the case!
The word "text" here is not an ALIAS it is the object/object.field that u want AngularJS do expose as the ng-model... so, that said, the solution in my case (object in the list as ng-model) was updating to: suggestion as suggestion.Detail for suggestion in SuggestionList
ng-options="suggestion as suggestion.Detail for suggestion in SuggestionList"
Ok that simply resolves the WhoIsSelectedFirstApproach, but if I want to pass the object to a function in the ng-change, using suggestion in the expression doenst work... (dont know why they used different expression logics for different ng-*) but to solve that problem figured that u can reference the ng-model field inside the ng-change: so I could manage that changing Function(suggestion) to Function(modelField) as follows:
ng-change="WhoIsSelected(SelectedSuggestion)"
SOLVED JS FIDDLE

Trouble parsing complex JSON response using JQuery (or just javascript)

Given the following function to grab JSON data from a Solr instance:
var url = "http://myserver:8080/solr/select?indent=on&version=2.2&q=(title:*Hollis* OR sub_title:*Hollis*+OR+creator:*Hollis*+OR+publisher:*Hollis*+OR+format:*Hollis*++OR+lcsh:*Hollis*++OR+loc_call_num_subject:*Hollis*+OR+note:*Hollis*++OR+toc:*Hollis*)AND+Match_Confidence:[.75+TO+*]&start=0&rows=3500&fl=Geocoded_Field,title,id_inst,Match_Confidence,Conjunct_Longitude1,Conjunct_Latitude1,Anchor,note,creator,format,language,pub_location,publisher,score&wt=json&group=true&group.field=title";
$.getJSON(url, function(data){
console.log("EXAMPLE TYPE:"+data.grouped.title.groups.docs[0].title);
});
How do I cycle through each response 'doc' (data posted below) and grab each "title" occurrence for example? I've tried numerous variations of data.grouped.title.groups.docs[0].title with no luck. I am thinking I just have the incorrect order in the data access string (data.grouped.title.groups.docs.title).
Sample data returned from query as copied and pasted from a browser:
{ "responseHeader":{
"status":0,
"QTime":902,
"params":{
"indent":"on",
"wt":"json",
"version":"2.2",
"rows":"3500", "fl":"Geocoded_Field,title,id_inst,Match_Confidence,Conjunct_Longitude1,Conjunct_Latitude1,Anchor,note,creator,format,language,pub_location,publisher,score",
"start":"0",
"q":"(title:*Hollis* OR sub_title:*Hollis* OR creator:*Hollis* OR publisher:*Hollis* OR format:*Hollis* OR lcsh:*Hollis* OR loc_call_num_subject:*Hollis* OR note:*Hollis* OR toc:*Hollis*)AND Match_Confidence:[.75 TO *]",
"group.field":"title",
"group":"true"}}, "grouped":{
"title":{
"matches":2533,
"groups":[{
"groupValue":"Thomas Hollis [and] Thomas Brand Hollis",
"doclist":{"numFound":3,"start":0,"maxScore":0.75592893,"docs":[
{
"title":"Thomas Hollis [and] Thomas Brand Hollis",
"Match_Confidence":0.894584,
"Conjunct_Latitude1":41.89,
"Conjunct_Longitude1":12.5,
"Geocoded_Field":[
"note"],
"pub_location":[
"1752"],
"Anchor":[
"Roma"],
"id_inst":[
"009360446"],
"language":["English"],
"format":["Other"],
"note":[
"Two bust portraits carved in bas-relief. One is of Thomas Hollis, the elder (1659-1731), and one of his friend and heir, Thomas Brand Hollis (ca.1719-1804). Portraits are framed together",
"Inscribed on front of each sculpture: Andrea Pozzi fece dal naturale; verso of Thomas Hollis inscribed: Ritratto del Sig: re Tommaso / Hollis, Cau: re Inglese, Termina= / to in Roma nel suo Giorno Nat= / alizio de i 14 Aprile 1752 in / Et di 32 Ani; verso of Thomas Brand Hollis inscribed: Ritratto dell'Illust: o Sig: re / Tommaso Brand, Caualiere / Inglese, Fatto in Roma / Nell' Anno 1752",
"Title taken from plaques",
"Framed and glazed"],
"creator":["Pozzi, Andrea, 1718-1769","Hollis, Thomas, 1720-1774, former owner"],
"score":0.75592893}]
}},
{
"groupValue":"The post of duty",
"doclist":{"numFound":24,"start":0,"maxScore":0.5459487,"docs":[
{
"title":"The post of duty",
"Match_Confidence":0.985783,
"Conjunct_Latitude1":42.4842,
"Conjunct_Longitude1":-76.4799,
"Geocoded_Field":[
"lcsh"],
"pub_location":[
"Coxsackie, N. Y"],
"Anchor":[
"Lansing"],
"id_inst":[
"006317718"],
"language":["English"],
"format":["Book"],
"note":[
"Published by request"],
"publisher":[
"F.C. Dedrick, Printer"],
"creator":["Zabriskie, Francis Nicoll, 1832-1891"],
"score":0.5459487}]
}},
{
"groupValue":"Discourses concerning government: in way of dialogue",
"doclist":{"numFound":1,"start":0,"maxScore":0.41996053,"docs":[
{
"title":"Discourses concerning government: in way of dialogue",
"Match_Confidence":0.95121,
"Conjunct_Latitude1":51.5142,
"Conjunct_Longitude1":-0.093145,
"Geocoded_Field":[
"pub_location"],
"pub_location":[
"London"],
"Anchor":[
"London"],
"id_inst":[
"006199101"],
"language":["English"],
"format":["Book"],
"note":[
"First published 1681 under title: Plato redivivus",
"Bound in old mottled calf, rebacked"],
"publisher":[
"Printed, and sold by A. Baldwin"],
"creator":["Neville, Henry, 1620-1694","Hollis, Thomas, 1720-1774, former owner"],
"score":0.41996053}]
}}]}}}
See this jsfiddle http://jsfiddle.net/ByxHV/
for (var i =0; i < data.grouped.title.groups.length; i++) {
var group = data.grouped.title.groups[i];
console.log(group.groupValue, group.doclist.numFound)
}​
I used JSON Pretty Print to examine the JSON
var titleList = [];
$.each(data.grouped.title.groups, function(index, value) {
$.each(value.doclist.docs, function(index, value) {
titleList.push(value.title);
});
});

Function not working properly. Please help

Hello I'm having trouble with the function setUpTranslation().
//The purpose of this function is to place the French phrases into the document and set up the event handlers for the mousedown and mouseup events.
//These are the arrays of the French phrases and English phrases that I have do place into the document:
var english = new Array();
english[0] = "This hotel isn't far from the Eiffel Tower.";
english[1] = "What time does the train arrive?";
english[2] = "We have been waiting for the bus for one half-hour.";
english[3] = "This meal is delicious";
english[4] = "What day is she going to arrive?";
english[5] = "We have eleven minutes before the train leaves!";
english[6] = "Living in a foreign country is a good experience.";
english[7] = "Excuse me! I'm late!";
english[8] = "Is this taxi free?";
english[9] = "Be careful when you go down the steps.";
var french = new Array();
french[0] = "Cet hôtel n'est pas loin de la Tour Eiffel.";
french[1] = "A quelle heure arrive le train?";
french[2] = "Nous attendons l'autobus depuis une demi-heure.";
french[3] = "Ce repas est délicieux";
french[4] = "Quel jour va-t-elle arriver?";
french[5] = "Nous avons onze minutes avant le départ du train!";
french[6] = "Habiter dans un pays étranger est une bonne expérience.";
french[7] = "Excusez-moi! Je suis en retard!";
french[8] = "Est-ce que ce taxi est libre?";
french[9] = "Faites attention quand vous descendez l'escalier.";
//function I'm having trouble with
function setUpTranslation(){
var phrases = document.getElementByTagName("p");
for (i =0; i<phrases.length; i++){
phrases[i].number =i;
phrases[i].childNodes[1].innerHTML =french[i];
phrases[i].childNodes[1].onmousedown =function(){
swapFE(event);
phrases[i].childNodes[1].onmouseup =function(){
swapEF(event);
};
};
}
//Below are the other two functions swapFE() and swapEF(). The purpose of the function swapFE() is to exchange the French phrase for the English translation
//The purpose of the function swapEF() is to exchange the English translation for the French phrase.
function swapFE(e){
var phrase =e.srcElement;
var parent =phrase.parentNode;
var idnum =parent.childNodes[0];
var phrasenum =parseInt(idnum.innerHTML)-1;
phrase.innerText =english[phrasenum];
}
function swapEF(e){
var phrase =e.srcElement;
var parent =phrase.parentNode;
var idnum =parent.childNodes[0];
var phrasenum =parseInt(idnum.innerHTML)-1;
phrase.innerText =french[phrasenum];
}
//Not sure if these are right. Thanks in advance!
Assuming that your HTML looks like this
<p><span>1</span><span></span></p>
<p><span>2</span><span></span></p>
...
<p><span>10</span><span></span></p>
Then all you need to do is to add the curly bracket after swapFE(event); (points for Mr Plunkett) and replace getElementByTagName with getElementsByTagName (you're missing an 's' in there).
One additional thing to note: If the English phrase is shorter than the French, the container might shrink when the onmousedown event fires. If this shrinkage causes the mouse cursor to be positioned outside the container, the subsequent onmouseup event will not be triggered. Of course, if you are using block elements (e.g. a <div>) instead of my assumed <span>, that likely isn't an issue. In any case, it's probably better to attach the event listeners to the <p> tags instead.

Categories

Resources