Switch between different website languages - documentElement.lang - javascript

I want to use a switch and individually target each English version of the website.
I tried using en/lang, but it does not work...
The variable populates a div with the string.
I could not use just the case 'en' since the English text is different for both SE and NO, so I need to target the English version of SE and NO individually.
switch (document.documentElement.lang) {
// ------------------------------ SE -----------------------------------
case 'en/se':
var heroTitle = 'This is an se english title';
break;
case 'se':
var heroTitle = 'This is a swedish title';
break;
// ------------------------------ NO -----------------------------------
case 'no/en':
var heroTitle = 'This is a no english title';
break;
case 'no':
var heroTitle = 'This is a no title';
break;
}

Look into i18next -- its by far the best way to do translations in JS.
https://www.i18next.com/
But to answer your question you'll want the full country code and lang. like en_US and en_SE I suppose. You can get the user's language with navigator.language

Related

Pseudocode for JavaScript Loop Assignment

I'm in a bit of a pickle, regarding my Pseudocode for an assignment I'm working on. It was marked incorrect saying I need to add a validation loop (which I thought I did). I'm pretty new to coding as my background is in IT Support. Any help explaining to me how to add a loop validation into my Pseudo would be much appreciated as Pseudo isn't really taught in this course and I'm a bit lost to be honest.
//PSEUDOCODE FOR assignment1.js
//input
/*
ONCLICK.PROMPT
FUNCTION
WINDOW.PROMPT
VAR CHOICE("Which website would you like?")
WHILE true
SWITCH (CHOICE CASE 1 - 3)
BREAK;
ELSE alert ("please enter a valid number")
RETURN TO FUNCTION
*/
Actual JS Script (Linked to a HTML).
function pressButton(){
var myElement= document.getElementById("websites");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
while (choice<0 || choice>3){
alert("please enter a valid number");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
default:
text = "error: please choose from the options above";
}
}
}
The best way to follow pseudo-code is keep it with the real code. As for your issue, the loop performs the validation. Outside the loop (after it) is when a valid choice has been made. Currently your switch is inside the validation loop, which means it'll run when the choice value is invalid. This matches your pseudo-code but unfortunatley your pseudo-code is wrong. Its a tough balance keeping the pseudo code small enough to match how a computer steps through the calculation and keeping actual code out of the pseudo text. Here's how I'd change it.
// ONCLICK
// GET CHOICE
// WHILE CHOICE INVALID
// ALERT OF INVALID CHOICE
// GET CHOICE AGAIN
// OPEN CHOICE
// END FUNCTION
Other tips. Your switch doesn't need a default unless an invalid choice can be made. Your validation should not include 0. This is also a great scenario for do...while (although that alert becomes an awkward scenario).
// ONCLICK
function pressButton(){
var myElement= document.getElementById("websites");
// GET CHOICE
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
// VAR CHOICE("Which website would you like?")
// WHILE invalid
while (choice <= 0 || choice > 3) {
// ALERT OF INVALID CHOICE
alert("please enter a valid number");
// GET CHOICE AGAIN
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
}
// OPEN CHOICE
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
}
// END FUNCTION
}
You should not run the switch statement if the value of choice is beyond the range. There is a bug in your code which will print the message only once and then pass the incorrect values of choice to the switch statement.
function pressButton(){
var myElement= document.getElementById("websites");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
while (choice<0 || choice>3) {
alert("please enter a valid number");
choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
}
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
}
}
The code above will keep asking the user to provide a number until user provides the right input. Also, you don't need the default case because the while loop will make sure that only the correct value is passed on to the switch block

Onclick event not working as expected. Any idea why?

I am working on a very simple quiz javascript project, with a score and a start button, that generates questions when it gets clicked. I started work in the JS code by adding an onclick event listener, but it is not working as expected. Here is the code snippet that is supposed to be working but doesn't work, with a few comments. Keep in mind that I am very inexperienced in Javascript, so I may have misused some JS methods.
function rng() {
return Math.floor(Math.random * 10)
}
let stbt = document.getElementById("start")
stbt.addEventListener("click", function() {
stbt.remove //should remove the start button when it gets clicked.
let q = document.createElement("p") //created an html paragraph.
switch(rng()) {
case 1:
let qc = document.createTextNode("What is the capital of Chile?")
q.appendChild(qc) /*this should theoretically insert text into the html paragraph that gets created when the start button gets clicked,
the switch statement that is switching the simple rng function should make it so that questions get generated randomly.*/
break;
case 2:
let qc = document.createTextNode("What is the highest mountain in Britain?")
q.appendChild(qc)
break;
case 3:
let qc = document.createTextNode("What is the smallest country in the world?")
q.appendChild(qc)
break;
case 4:
let qc = document.createTextNode("Alberta is a province of which country?")
q.appendChild(qc)
break;
case 5:
let qc = document.createTextNode("How many countries still have the shilling as currency?")
q.appendChild(qc)
break;
case 6:
let qc = document.createTextNode("Which is the only vowel not used as the first letter in a US State?")
q.appendChild(qc)
break;
case 7:
let qc = document.createTextNode("What is the largest country in the world?")
q.appendChild(qc)
break;
case 8:
let qc = document.createTextNode("Where would you find the River Thames?")
q.appendChild(qc)
break;
case 9:
let qc = document.createTextNode("What is the hottest continent on Earth?")
q.appendChild(qc)
break;
case 0:
let qc = document.createTextNode("What is the longest river in the world?")
q.appendChild(qc)
break;
}
})
It is not the listener at fault here, but a number of small errors that are causing your code not to work.
You are not calling two functions: Math.random should be Math.random(), and stbt.remove should be stbt.remove().
Because of the way you have written your switch your qc variable is scoped across all your case statements, so you can't declare it again. You can fix this by either declaring it outside of the switch and assigning it in the case statements, or using braces to scope the variable to each case.
let qc; //<--- declare qc;
switch (rng()) {
case 1:
qc = document.createTextNode("What is the capital of Chile?")
...
break;
case 2:
qc = document.createTextNode("What is the highest mountain in Britain?")
...
or
switch (rng()) {
case 1: { //<--- braces to scope variable declaration
let qc = document.createTextNode("What is the capital of Chile?")
...
break;
}
case 2: {
let qc = document.createTextNode("What is the highest mountain in Britain?")
...
break;
}
case 3: {
...
Lastly, you never append your <p> element to the DOM. You'll need to either query an element to append to, or as in the example below, append directly to the document.body
The switch statement tends to be quite verbose and so it helps to avoid duplication as much as possible. Instead of appending the new text node within each case you can instead move it after the switch and call it just once.
stbt.addEventListener("click", function () {
...
let qc;
switch (rng()) {
case 1:
...
}
// Avoid duplication by appending once at the end
q.appendChild(qc)
document.body.appendChild(q) //<--- append <p> to DOM
});
function rng() {
return Math.floor(Math.random() * 10); //<--- parentheses needed to call function;
}
const stbt = document.getElementById("start");
stbt.addEventListener("click", function () {
stbt.remove(); //<--- parentheses needed to call function;
let q = document.createElement("p");
let qc; //<--- declare qc;
switch (rng()) {
case 1: {
let qc = document.createTextNode("What is the capital of Chile?")
break;
}
case 2:
qc = document.createTextNode("What is the highest mountain in Britain?")
break;
case 3:
qc = document.createTextNode("What is the smallest country in the world?")
break;
case 4:
qc = document.createTextNode("Alberta is a province of which country?")
break;
case 5:
qc = document.createTextNode("How many countries still have the shilling as currency?")
q.appendChild(qc)
break;
case 6:
qc = document.createTextNode("Which is the only vowel not used as the first letter in a US State?")
break;
case 7:
qc = document.createTextNode("What is the largest country in the world?")
break;
case 8:
qc = document.createTextNode("Where would you find the River Thames?")
q.appendChild(qc)
break;
case 9:
qc = document.createTextNode("What is the hottest continent on Earth?")
break;
case 0:
qc = document.createTextNode("What is the longest river in the world?")
break;
}
// Avoid duplication by appending once at the end
q.appendChild(qc)
document.body.appendChild(q) //<--- append <p> to the DOM
});
<button type="button" id='start'>Start</button>
Making it more general
Using a switch can be very clear in showing what is happening, but it does lead to a lot of duplication. If you wanted to add a question you would need to add a whole new case statement as well as change the constant within your rng() function. To avoid this you might want to think about other structures that might serve your purpose.
Here is an example using an Array to store the questions which is accessed by index using the returned value from the rng() (which has been changed to accept a max value). With this structure, adding a question is simply a matter of adding to the array, the rest takes care of itself.
function rng(max) {
return Math.floor(Math.random() * max)
}
const questions = [
"What is the capital of Chile?",
"What is the highest mountain in Britain?",
"What is the smallest country in the world?",
"Alberta is a province of which country?",
"How many countries still have the shilling as currency?",
"Which is the only vowel not used as the first letter in a US State?",
"What is the largest country in the world?",
"Where would you find the River Thames?",
"What is the hottest continent on Earth?",
"What is the longest river in the world?",
]
const stbt = document.getElementById("start")
const div = document.getElementById("questions")
stbt.addEventListener("click", function () {
// pass the length of the questions array as the max value for the rng()
const questionIndex = rng(questions.length);
const question = questions[questionIndex];
stbt.remove();
const q = document.createElement("p");
const qc = document.createTextNode(question)
q.appendChild(qc)
div.appendChild(q)
});
<button type="button" id='start'>Start</button>
<div id='questions'></div>

Javascript switch not working with <option> tag values

I have the following HTML:
<select id="rankBox">
<option value="0">100</option>
<option value="1">150</option>
<option value="2">200</option>
<option value="3">250</option>
<option value="4">300</option>
<option value="5">350</option>
<option value="6">400</option>
</select>
<input type="Submit" id="button1" value="Generate" onclick="doStuff()">
and the following Javascript:
function doStuff() {
var choice = $("#rankBox option:selected").val();
console.log(choice);
switch (choice) {
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
In short, I have a switch statement which is supposed to check the value of the option the user has selected. As you may see, I have added console.log to see if the problem is with acquiring the user's input, but that is not the issue. The issue is the switch statement, which just does not work.
Am I using wrong syntax or something?
jsFiddle: http://jsfiddle.net/3qTHW/2/ (jsFiddle doesn't work in my browser at all, says doStuff() is not defined)
Thanks in advance.
It's not an integer, it's a string, as all values from an element are strings.
You'll have to either parse it as an integer :
function doStuff() {
var choice = parseInt( $("#rankBox option:selected").val(), 10);
....etc
or change the switch to work with strings (you should be trimming)
switch ( $.trim(choice) ) {
case '0':
case '1':
....etc
This was an easy problem, by looking at the code one could see that the line var choice = $("#rankBox option:selected").val(); is adding string to variable choice. And that is the reason none of the case statements worked and the default code executed.
The best way not to run into such problems is to "Debug" your JavaScript code properly. This will save you a lot of precious time and you will find the root cause to each problem yourself.
To debug your code, you can use Firebug extension in Firefox. This will actually stop the code execution for you and guide you line by line telling you the state of each variable at every line of code. So in case of your problem, all I did was add your code in .html file and ran it in Firefox with "Debugger" points specified. The JS code looked like this.
function doStuff() {
var choice = $("#rankBox option:selected").val();
debugger; // This is the point where the debugging starts
console.log(choice); // console.log wont help as it did not tell me the type
switch (choice) { // Here Firebug tells me that choice is actually a string
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
Note I put a "debugger" above console.log(). From this point onward, the code stopped at each line and I could see the value in each variable. This helped me notice string value in choice.
Happy Debugging :)
Use javascript parseInt() method like this :
var choice = parseInt($("#rankBox option:selected").val());

use regex to verify a text using a multiple if statements in javascript/jquery

i need to identify the data/text being submitted from <input> if it contains any of the following. youtube, vimeo,normal website, jpg/png, plain text
if a youtube link is found {
//do something
} else if a vimeo link is found {
//do something
} else if a normal website is found {
//do something
} else if a (jpg/png) is found {
//do something
} else just a text {
} //do something
as of the moment is my syntax. the youtube & vimeo regex format were taken from other posts. but im not sure how to create the proper regex for the others.
ive tried some regex generator but its so complicated to use
im also interested to know if this is the proper way of executing multiple conditional statement.
$(function() {
$(document).on('click','.submit', function () {
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
if (data.match(youtube)) {
alert("utube");
}
else if (data.match(vimeo)) {
alert("vimeo");
}
else if ...
});
});
There is a million different ways to do this.
The other regex you need are roughly bellow. Also it will save you a bit of a headache if you lowercase your data
var data = $("#input").val.toLowerCase();
Web url
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/
PNG / JPG is at end of the string
/(png|jpg|jpeg)$/
Plain text i guese would be what ever is left
The most efficient way is also to use a switch statement not a big if else
like this http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
I would suggest using a switch statement when you have multiple regex conditions to check for:
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
var normalWebsite = /^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*#)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+))?$/;
var image = /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/;
switch (true) {
case youtube.test(data):
alert('youtube');
break;
case vimeo.test(data):
alert('vimeo');
break;
case normalWebsite.test(data):
alert('normal website');
break;
case image.test(data):
alert('image');
break;
default:
// Here we are assuming anything that doesn't match the above is plain text.
// You will need an additional regex if you want to make sure this doesn't contain html or code.
alert('Plain text');
break;
}

Is there a way to use non-octal literals in a string?

I have to filter out characters in a form. Thus I have implemented a filtering-out algorithm that works quite well and makes use of different filters (variables) according to different contexts; I have to make extended use of accented letters too.
Example:
gFilterALPHA1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-–àâäéèêëîïôöùüûÀÂÄÉÈÊËÎIÔÖÙÛÜæÆœŒçÇ ";
Strangely enough, letters é (e acute) or è (e grave) are taken into account (seen as such), while others such as à (a grave) are not. I found the solution is using octal litterals — for instance \340 or \371 for a grave or u grave respectively.
Q1. Any clue about why é (e acute) is succesfully parsed straightforwardly while other accented letters are not?
Q2. Since writing a long string of octal literals is both cumbersome and error-prone when one wants to check or add values, does anyone have a better idea or know of a workaround?
Thanks.
OK, here is the code thg435 thinks it useful to take a look at.
function jFiltre_Champ(event, NomDuFiltre)
{
var LeChamp=event.target.value; // value est de type ARRAY
switch (NomDuFiltre)
{
case "NUM1":
LeFiltre=gFiltreNUM1;
Msg=gMessageNUM1;
break;
case "ALPHA1":
LeFiltre=gFiltreALPHA1;
Msg=gMessageALPHA1;
break;
case "DATE1":
LeFiltre=gFiltreDATE1;
Msg=gMessageDATE1;
break;
case "ALPHANUM1":
LeFiltre=gFiltreALPHANUM1;
Msg=gMessageALPHANUM1;
break;
case "ALPHANUM2":
LeFiltre=gFiltreALPHANUM2;
Msg=gMessageALPHANUM2;
break;
}
Longueur=LeFiltre.length;
for (i=0; i<LeChamp.length; i++)
{
leCar = LeChamp.charAt(i);
for (j = 0; j < Longueur; j++)
{
if (leCar==LeFiltre.charAt(j)) break;
}
if (j==Longueur)
{
alert(Msg);
/*Cf doc. pour l'algorithme de la méthode slice*/
document.getElementById(event.target.id).value=event.target.value.slice("0", i);
break;
}
}
}
Here is a English-style version: (regarding (2))
function jform_input_filter(event, filterName)
{
var current_input = event.target.value; // the value is an array
switch (filterName)
{
case "NUM1":
current_filter = gFilterNUM1;
Msg = gMessageNUM1;
break;
case "ALPHA1":
current_filter = gFilterALPHA1;
Msg = gMessageALPHA1;
break;
case "DATE1":
current_filter = gFilterDATE1;
Msg = gMessageDATE1;
break;
case "ALPHANUM1":
current_filter = gFilterALPHANUM1;
Msg = gMessageALPHANUM1;
break;
case "ALPHANUM2":
current_filter = gFilterALPHANUM2;
Msg = gMessageALPHANUM2;
break;
}
length = current_filter.length;
for (i = 0; i < current_input.length; i++)
{
leCar = current_input.charAt(i);
for (j = 0; j < length; j++)
{
if (leCar==current_filter.charAt(j)) break;
}
if (j == length)
{
alert(Msg);
/*Cf doc. pour l'algorithme de la méthode slice*/
document.getElementById(event.target.id).value=event.target.value.slice("0", i);
break;
}
}
Comments:
Personally I should not think this code useful to give an answer to the original question;
variables and comments are in French, which may render it difficult to read for some — sorry about that;
this function is associated to an 'onchange' event from within a HTML form;
'g' variables (e.g. gFiltreALPHANUM2) are broad-scope vectors defined elsewhere in the same .js file so that they are accessible to the function.
Bergi is probably right: your file is probably saved or delivered with the wrong encoding. Consider UTF-8 as a well supported encoding for the Unicode character set. To test this idea, you can temporarily adjust your script to output the a-with-acute-accent into the page, whether in a field or as a text node. Use the verbatim character in your string literal, not its octal escape code. If it comes out garbled, then the character didn't make it in its pristine form into the browser and you've got an encoding problem.
If the encoding problem is confirmed, you'll need to save your file correctly, or adjust the response character encoding, which depends on your particular web server. You can find the current encoding as delivered by your web server by using Fiddler and inspecting the Content-Type response header. If the web server already thinks your file is in the right encoding (preferably, as indicated, UTF-8), then check your text editor to make sure it saves the JavaScript file in the same exact encoding.
I'm writing this as an answer because I don't think I can comment directly on the question.

Categories

Resources