Function not working properly. Please help - javascript

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.

Related

How to pass a variable from one function to another function CDATA

I am very new to JavaScript.
Here is my problem, I have a form with a "cp" field from which I retrieve the value in real time
This is achieved in a function.
Then I would like to use my result in the mondial relay widget to override the plugin default
After testing several things, I give you my last try which does not show me the "cp" variable in the second function.
So I would like to replace PostCode: "6000" with cp
<input class="form-control" type="text" name="cp" value="" id="cp" required="required" />
<javascript>
var input ;
//le code postal
$(document).ready(function(){
$("#cp").keyup(function(){
const cptest = document.querySelector('[name="cp"]');
console.log (cptest);
var input = document.getElementById("cp").value;
console.log (input);
return input;
});
});
//<![CDATA[
console.log (input);
// Initialiser le widget après le chargement complet de la page
$(document).ready(function () {
// Charge le widget dans la DIV d'id "Zone_Widget" avec les paramètres indiqués
$("#Zone_Widget").MR_ParcelShopPicker({
// Selecteur de l'élément dans lequel est envoyé l'ID du Point Relais (ex: input hidden)
Target: "#Target_Widget",
// Selecteur de l'élément dans lequel est envoyé l'ID du Point Relais pour affichage
TargetDisplay: "#TargetDisplay_Widget",
// Selecteur de l'élément dans lequel sont envoysé les coordonnées complètes du point relais
TargetDisplayInfoPR: "#TargetDisplayInfoPR_Widget",
// BDTEST est utilisé pour les tests => un message d'avertissement apparaît
Brand: "BDTEST ",
// Pays utilisé pour la recherche: code ISO 2 lettres.
Country: "BE",
// Code postal pour lancer une recherche par défaut
PostCode: "6000",
// Activer l'affichage Responsive.
Responsive: true,
// Fonction de callback déclenché lors de la selection d'un Point Relais
OnParcelShopSelected:
AllowedCountries: "FR,BE,NL,LU",
});
});
// ]]>
</javascript>
There are a few issues with your code:
when working with jQuery you should use its powers and not mix it with document.querySelector()
input was declared locally within your jQuery event handler and was therefore invisible.in the global scope
input is only defined properly after the first keyup event (which I changed to input as this also includes mouse based input actions)
var input ;
//le code postal
$(function(){
$("#cp").on("input",function(){
input=this.value;
console.log(input);
// anything you want to happen to
// $("#Zone_Widget").MR_ParcelShopPicker(..)
// needs to happen here ...
});
});
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<input class="form-control" type="text" name="cp" value="" id="cp" required="required" />

Picking multiple random values from array [duplicate]

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 4 months ago.
Does anyone know how you can pick more than one random element from an array? The code below is a simplified version of my code, but i think it should be enough.
My code picks a random quote from the array, then fills a div with the random string. But here comes my question, how do i get a new quote when userinput === quoteRandom. The code should be able to do this multiple times.
let quote_array = [
'Gresset er grønnere på andre siden av gjerdet',
'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge',
'Jeg skulle ikke spise den, jeg skulle bare smake på den',
'Nøtter er ikke noe for en hel rev'
];
//Pick random quote
let quoteRandom = sitat_array[Math.floor(Math.random() * sitat_array.length)];
//Fill a div with quoteRandom
function fillQuote() {
div.innerText = quoteRandom;
}
//If userinput === quoteRandom
function newQuote() {
fillQuote();
}
If you mutate the origanal array with sort and pop, every time you can get a random element form the rest of the array. So you will never get a quote again, only all the elements are poped, and the array is reinitialized.
let quote_array = [];
function getaquote() {
if (quote_array.length === 0) {
quote_array = [
'Gresset er grønnere på andre siden av gjerdet',
'Å være sliten og nedfor og er ikke et tegn på svakhet, mest sannsynlig har du vært sterk for lenge',
'Jeg skulle ikke spise den, jeg skulle bare smake på den',
'Nøtter er ikke noe for en hel rev'
];
}
quoteRandom1 = quote_array.sort(() => (Math.random() > .5) ? 1 : -1).pop();
console.log(quoteRandom1);
}
<button onclick="getaquote()">get a quote</button>

Button not working discord.js discord-buttons

hello so i write this code
module.exports.run = async (Client, message, args, prefix) => {
if (!message.content.startsWith(prefix)) return;
disbut(Client);
let button1 = new disbut.MessageButton()
.setStyle("green") //default: blurple
.setLabel("créer un channel") //default: NO_LABEL_PROVIDED
.setID("create"); //note: if you use the style "url" you must provide url using .setURL('https://example.com')
let button2 = new disbut.MessageButton()
.setStyle("red") //default: blurple
.setLabel("fermer un channel") //default: NO_LABEL_PROVIDED
.setID("close"); //note: if you use the style "url" you must provide url using .setURL('https://example.com')
message.channel.send("Cliquer sur les boutons pour effectuer une action ", {buttons : [button1, button2] });
};
if i execute my command the texte is send in my channel but not the button
and i dont understand why and i dont have any error
thanks for your help :)
In Discord.js v13, the send method only takes a single parameter. Discord.js is only looking at "Cliquer sur les boutons..." and not the second object you are providing.
Instead, use a single MessageOptions object:
message.channel.send({
content: "Cliquer sur les boutons pour effectuer une action ",
buttons: [button1, button2]
});
For more information, see this section in the Discord.js guide.

Regex: get numbers after a matching pattern with multi lang support

Expected Income/Output
Input: Longines, retailed by Barth, Zurich, ref. 22127, movement no. 5770083,
Desired Output: 5770083
Only digits from this I will build: {"Movement Number": 5770083}
I believe I will need to run multiple regexes against each string as I need to know the following:
Which title belongs to which string ie movement no.= 5770083 etc
Multiple different languages will be used for the same title, for example:
Movement number variations:
Movement no.
mouvement signés.Numérotée
no
MVT
jewels #
Werk-Nr.
Current regex: /movement no. ([^\s]+)/
With the above regex it will also pick up the ,.
It is also case insensitive.
Test String
Longines. A very fine and rare stainless steel water-resistant
chronograph wristwatch with black dial and original box\nSigned
Longines, retailed by Barth, Zurich, ref. 22127, movement no. 5770083,
case no. 46, circa 1941\nCal. 13 ZN nickel-finished lever movement, 17
jewels, the black dial with Arabic numerals, outer railway five minute
divisions and tachymetre scale, two subsidiary dials indicating
constant seconds and 30 minutes register, in large circular
water-resistant-type case with flat bezel, downturned lugs, screw
back, two round chronograph buttons in the band, case and movement
signed by maker, dial signed by maker and retailer\n37 mm. diam.
Test String French
MONTRE BRACELET D'HOMME CHRONOGRAPHE EN OR, PAR LONGINES\n\nDe forme
ronde, le cadran noir à chiffres arabes, cadran auxiliaire pour les
secondes à neuf heures et totalisateur de minutes à trois heures,
mouvement mécanique 13 Z N, vers 1960, poids brut: 44.49 gr., monture
en or jaune 18K (750)\n\nCadran Longines, mouvement no. 3872616, fond
de boîte no. 5872616\nVeuillez noter que les bracelets de montre
pouvant être en cuirs exotiques provenant d'espèces protégées, tels le
crocodile, ils ne sont pas vendus avec les montre même s'ils sont
exposés avec celles-ci. Christie's devra retirer et conserver ces
bracelets avant leur collecte par les acheteur
You can use
\b((?:Movement|mouvement) no\.|mouvement signés\.Numérotée|no|MVT|jewels #|Werk-Nr\.) (\d+)
https://regex101.com/r/thL0wt/1
Start at a word boundary, then inside a capturing group, alternate between all the different possible phrases you want before a number - then, match a space, and capture numeric characters in another group. Your desired result will be in the first and second capturing groups.
const input = `Longines. A very fine and rare stainless steel water-resistant chronograph wristwatch with black dial and original box\nSigned Longines, retailed by Barth, Zurich, ref. 22127, movement no. 5770083, case no. 46, circa 1941\nCal. 13 ZN nickel-finished lever movement, 17 jewels, the black dial with Arabic numerals, outer railway five minute divisions and tachymetre scale, two subsidiary dials indicating constant seconds and 30 minutes register, in large circular water-resistant-type case with flat bezel, downturned lugs, screw back, two round chronograph buttons in the band, case and movement signed by maker, dial signed by maker and retailer\n37 mm. diam.
MONTRE BRACELET D'HOMME CHRONOGRAPHE EN OR, PAR LONGINES\n\nDe forme ronde, le cadran noir à chiffres arabes, cadran auxiliaire pour les secondes à neuf heures et totalisateur de minutes à trois heures, mouvement mécanique 13 Z N, vers 1960, poids brut: 44.49 gr., monture en or jaune 18K (750)\n\nCadran Longines, mouvement no. 3872616, fond de boîte no. 5872616\nVeuillez noter que les bracelets de montre pouvant être en cuirs exotiques provenant d'espèces protégées, tels le crocodile, ils ne sont pas vendus avec les montre même s'ils sont exposés avec celles-ci. Christie's devra retirer et conserver ces bracelets avant leur collecte par les acheteur`;
const matches = {};
let match;
const pattern = /\b((?:Movement|mouvement) no\.|mouvement signés\.Numérotée|no|MVT|jewels #|Werk-Nr\.) (\d+)/gmi;
while (match = pattern.exec(input)) {
matches[match[1]] = match[2];
// or, if you only want a single object:
const obj = {
[match[1]]: match[2]
};
}
console.log(matches);
For movement no. specifically you'll want this regex to get rid of the comma:
movement no. ([^\s\W]+)
In regards to the languages, a set of if statements performing the appropriate term that you want to test against is the only way I can think of unless the RegExp object allows for string substitution. Sorry for not being more help in that area.
You are using negated character class [^\s]+, which matches everything except whitespace. So, if there's another character you don't want to match, i.e. comma ,, then add it to this class: [^\s,].
And you can follow same logic for any character you don't want to match.
var input = "Longines, retailed by Barth, Zurich, ref. 22127, movement no. 5770083";
var output = input.match(/(?<=movement no. )\d+/)

internationalization with jQuery

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.

Categories

Resources