Comparing string values and showing correct 'answers' in javascript - javascript

I am fairly new to Javascript and am trying to learn to write a program that shows a text in one language (eg. Spanish) and has an input box, where the user will type the translated (eg. English) word. The user input would then be compared to the translated word to see if they are the same. I also want to allow some tolerance in case the user inputs a word without an accent if there is supposed to be one (eg. esta instead of está) it won't be counted wrong. If they are not the same I want to be able to show the correct word compared to what the user put. I've been trying to work on this for quite some time but have been getting stuck frequently (for instance, when I run the other function to check the values it opens a new instance when I want it all to be displayed on the same page). Any help with this would be greatly appreciated. Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Flashcards</title>
</head>
<body>
<script>
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
</script>
<p>English Translation: <input id="english_word" type="text" name="LastName" value="" ></p>
<input type="button" id="myBtn" onclick="check()" value="Check">
<input type="button" id="button" onclick="differentword()" value="Different Word">
<script>
function check()
{
var english_word= document.getElementById('english_word').value;
if (english_word == English) {
document.write("Correct");
}
else {
document.write("Wrong: ");
document.write(Spanish+" in English is "+English);
}
}
function differentword() {
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
}
</script>
</body>
</html>
Or, if you want to see how it runs, you can check it out here https://code.sololearn.com/WXHZ5aAcE3dg/#html.

You got 2 problems here.
You haven't set the current <input id="english_word" type="text" name="LastName" value=""> any value at all (by both html/js). You should set it to the current word (as a string) to manipulate it later.
the if statement if (english_word == English) is broken because it checks if english word, which is a string, equals to an array. and its not, and will never be.
However, checking if the current string word equals to a string, is not a good way in my option. I would like better to use an index to current word that is showing and manipulating that index.
What I suggest is you fix the above by using a new variable: current_word_index, so you can use it in program to check the answer by knowing the current word that is showing.
This next code is just an example of how to currently retrieve by index from arrays:
var current_word_index = 0; // this 0 will change to rand()
var english_word = ["hi","bye"];
english_word[current_word_index];
// english_word will be string "hi".
Here's my full answer:
https://fiddle.jshell.net/j44fjh35/15/

Summary of your question
My understanding is your trying to test the users knowledge on a secondary language ie: Spanish, French etc.
Solution
Switch or If statements are ways to test and compare variables against one another
what you will need to do is first of all convert the string variable to lowercase to ensure that what ever the user types in is always the same.
You will also need to fix some of your code.
So lets look at that first...
var number = parseInt((Math.random()*1));
var spanish_word = ["hola","adios"];
spanish_word is an array which starts from 0 not 1.
Your randomly generated number stored as "number", will equally need to be 0 or 1, simple integer will be sufficient.
Unless your submitting this to a server to be handled by some backend code in PHP or ASP etc, you dont need the "name" attribute here
name="LastName"
You are then over-riding the array
At the start you are setting the array with the following values
var english_word = ["hi","bye"];
But when you click the button to check if you have the right answer
You are erasing the above and telling it to be what ever the user typed in
var english_word= document.getElementById('english_word').value;
There is no need to keep setting and un-setting the array
Try to use better naming convensions for your variables
abbreviate them with what data types they are:
arrEnglishWord to symbolise its an array
strEnglishWord to symbolise it is a string
intEnglishISOCode to symbolise a numerical integer
blEnlish to symbolise a boolean
A lot of code repetition:
Using the an event listener you can save the code repetition
document.addEventListener("DOMContentLoaded", differentword, false);
will make the function differentword run when the page loads, allowing you to get rid of the repeated code at the top
Solution
We need to make the comparison fair (ie not case sentisive)
var strAnswerGiven = english_word.toLowerCase();
var strCorrectAnswer = English.toLowerCase();
if (strAnswerGiven == strCorrectAnswer) {
var arrSpanishWords = ["Hola", "Adios", "Purta", "Luz"];
var arrEnglishWords = ["Hello", "Goodbye", "Door", "Light"];
var strWord = undefined;
var divAnswer = undefined;
function funCheck(elName){
var stAnswer = document.querySelector("#" + elName).value;
var stAnswerGiven = stAnswer.toLowerCase();
var stAnswerExpected = strWord.toLowerCase();
if (stAnswerGiven == stAnswerExpected){
divAnswer.style.color = "#0F0";
divAnswer.innerHTML = "Correct";
}else{
divAnswer.style.color = "#F00";
divAnswer.innerHTML = "Wrong";
}
}
function funNewQuestion(){
var intRandomQNum = parseInt(Math.random() * arrSpanishWords.length);
var elDisplayQuestion = document.getElementById("divWord");
divAnswer = document.getElementById("divAnswerIs");
divAnswer.innerHTML = "";
elDisplayQuestion.innerHTML = arrSpanishWords[intRandomQNum];
strWord = arrEnglishWords[intRandomQNum];
}
document.addEventListener("DOMContentLoaded", funNewQuestion(), false);
Word: <div id="divWord"></div><div id="divAnswerIs"></div>
Answer: <input type="text" id="frmTxtAnswer">
<button id="check" onclick="funCheck('frmTxtAnswer')">Check Answer</button>
<button id="check" onclick="funNewQuestion()">Next Question</button>

Related

Can't get values past array[0] to translate properly

Okay, to start with I should mention this is a very small personal project, and I've only have a handful of coding classes several years ago now. I can figure out a lot of the (very) basics, but have a hard time troubleshooting. I'm in a little bit over my head here, and need a dumbed down solution.
I'm trying to put together a VERY simple translator that takes in a word or sentence from the user via a text input box, puts each word of the string into an array, translates each word in order, then spits out each translated word in the order it was input. For example, typing "I like cats" would output "Ich mag Katze" in German.
I've got most of it, but I CAN'T get anything but the first array element to translate. It comes out like "Ich like cats".
I've used a loop, probably because I'm an amateur and don't know another way of doing this, and I'd rather not use any libraries or anything. This is a very small project I want to have a couple of friends utilize locally; and I know there has to be some very simple code that will just take a string, put it into an array, swap one word for another word, and then output the results, but I'm damned if I can make it work.
What I currently have is the closest I've gotten, but like I said, it doesn't work. I've jerry-rigged the loop and clearly that's the totally wrong approach, but I can't see the forest for the trees. If you can help me, please make it "Javascript for Babies" picture book levels of simple, I cannot stress enough how inexperienced I am. This is just supposed to be a fun little extra thing for my D&D group.
function checkForTranslation(input, outputDiv) {
var input = document.getElementById("inputTextField").value;
var outputDiv = document.getElementById("translationOutputDiv");
input = input.toLowerCase();
//puts user input into an array and then outputs it word by word
const myArray = input.split(" "); //added .split, thank you James, still otherwise broken
let output = "";
let translation = "";
for (let i = 0; i < myArray.length; i++) {
output += myArray[i]; //up to here, this works perfectly to put each word in the string into an array
//prints all words but doesnt translate the second onwards
translation += myArray[i];
if (output == "") {
//document.getElementById("print2").innerHTML = "Translation Here";
}
else if (output == "apple") {
translation = "x-ray";
}
else if (output == "banana") {
translation = "yak";
}
else {
translation = "???";
}
output += " "; //adds a space when displaying original user input
} // END FOR LOOP
document.getElementById("print").innerHTML = output; //this outputs the original user input to the screen
document.getElementById("print3").innerHTML = translation; //this should output the translated output to the screen
} // END FUNCTION CHECKFORTRANSLATION
What it looks like
P.S. I'm not worried about Best Practices here, this is supposed to be a quickie project that I can send to a couple friends and they can open the HTML doc, saved locally, in their browser when they want to mess around with it if they want their half-orc character to say "die by my hammer!" or something. If you have suggestions for making it neater great, but I'm not worried about a mess, no one is going to be reading this but me, and hopefully once it's fixed I'll never have to read it again either!
Since it is a manual simple translation, you should just create a "dictionary" and use it to get the translations.
var dictionary = {
"apple": "x-ray",
"banana": "yak"
}
function checkForTranslation() {
var input = document.getElementById("inputTextField").value.toLowerCase();
var words = input
.split(' ') // split string to words
.filter(function(word) { // remove empty words
return word.length > 0
});
var translatedWords = words.map(function(word) {
var wordTranslation = dictionary[word]; // get from dictionary
if (wordTranslation) {
return wordTranslation;
} else { // if word was not found in dictionary
return "???";
}
});
var translatedText = translatedWords.join(' ');
document.getElementById("translationOutputDiv").innerHTML = translatedText;
}
document.getElementById('translate').addEventListener('click', function() {
checkForTranslation();
});
<input type="text" id="inputTextField" />
<button id="translate">translate</button>
<br/>
<hr />
<div id="translationOutputDiv"></div>
Or if you want it a little more organized, you could use
const dictionary = {
"apple": "x-ray",
"banana": "yak"
}
function getTranslation(string) {
return string
.toLowerCase()
.split(' ')
.filter(word => word)
.map(word => dictionary[word] || '???')
.join(' ');
}
function translate(inputEl, outputEl) {
outputEl.innerHTML = getTranslation(inputEl.value);
}
document.querySelector('#translate').addEventListener('click', function() {
const input = document.querySelector('#inputTextField');
const output = document.querySelector('#translationOutputDiv');
translate(input, output);
});
<input type="text" id="inputTextField" />
<button id="translate">translate</button>
<br/>
<hr />
<div id="translationOutputDiv"></div>

Making secret language useing charAt

I need to make a textbox with in there a word when i click on a button that word needs to convert into numbers useing charAt and that number needs to get +2 and than converted back into words and that word needs to get alerted i dont know what to do i find this really hard i made a function that is useless but i just want to show you what i did please help :)
function codeer(){
var woord2 = document.getElementById("woord")
var woordterug = woord2.charAt(0)
var woord234 = document.getElementById("woord");
var woord23 = woord234.charAt(str.length+2);
}
You could get the char code with String#charCodeAt from the character add two and build a new string with String.fromCharCode.
function codeer() {
var woord = document.getElementById("woord").value,
coded = '',
i;
for (i = 0; i < woord.length; i++) {
coded += String.fromCharCode(woord.charCodeAt(i) + 2);
}
console.log(coded);
}
<input id="woord" /> <button onclick="codeer()">cooder</button>
You should search the internet for a JavaScript rot13 example. In that code, you just need to replace the 13 with a 2, and it should work.

I want to obtain a certain part of text from a large webpage using Javascript, how do I?

There is a certain webpage which randomly generates a number, for example "Frequency : 21". I am trying to create a script which takes the number, 21, and compares it to another variable, then to an if else function. Basically, I've completed most of it, but I can't obtain the number 21. And since it is random, I can't put in a fixed value.
Can anyone help me out?
My code goes like:
setTimeout(MyFunction,5000)
function MyFunction(level,legmin) {
var level = x
var legmin = 49
if (level <= legmin) {
location.reload(true)
}
else {
alert("Met requirements.")
}
where the address of the text I want is:
html>body>div#container>div#contentContainer>div#content>
div#scroll>div#scrollContent>div>div>div#pkmnappear>form>p (x in the code above).
A quick-n-dirty solution without regex.
var lookFor = "Frequency : ";
var text = document.querySelector("#pkmnappear>form>p").textContent;
var level = text.substr(text.indexOf(lookFor) + lookFor.length).split(" ")[0];
This assumes the number will be followed by a space

New to javascript, how to assign an input value to a submit button?

I'm new to javascript and need help with a piece of my code. I am suppose to create a text box that a user can input a number and the function will then roll that many dice. I also need to set limits so a user can't enter -10 or 100 because it is only 1-6. So it looks like this:
var theInput = document.getElementById('num').value;
theInput = parseInt(theInput);
if (theInput < 1) {
theInput="1";
}
else if (theInput > 6) {
theInput = "6";
}
The part I'm stuck on is how I am suppose to link a text box to this piece of code that will then run through my function for dice rolling.
<script type="text/javascript">
function SelectImage6() {
document.getElementById('outputDiv').innerHTML ='';
for(i=0; i<6; i++){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
document.getElementById('outputDiv').innerHTML +=
'<img alt="die image" src="' + imgName2+'" />';
}
}
</script>
<body>
<div style="text-align:center">
<input type="button" value="Click to Roll" onclick="SelectImage6();">
<p id="outputDiv">
<img id="dieImg2" alt="die image"
src="../images/die2.gif" >
</p>
</div>
Where do I assign the var theInput within my code? Any help would be greatly appreciated. Thanks!
Well first you should create the textbox in the html like this:
<input type="text" id="num">
Then have people push a button to start your javascript code. So use the button you already have. Then when the SelectImage6() function is called on the button click, you just put the top javascript code (the one checking the input) into the function SelectImage6() and you will have a nice function that does it all.
To answer the specifics of your question, it makes most sense to get the number of dice to roll inside the SelectImage6 function. To make things nice and clean, you might want to encapsulate that functionality:
// returns the number of dice the user entered. if the user entered a non-numeric
// value, this function will throw an exception. if the user entered less than
// one, the value will be clamped to 1, and if the user entered more than six, the
// value will be clamped to 6.
function getNumDice() {
'use strict';
var numEntered = parseInt( document.getElementById('num').value );
if( isNaN( numEntered ) ) throw 'The number of dice must be numeric.';
if( numEntered < 1 ) numEntered = 1;
if( numEntered > 6 ) numEntered = 6;
return numEntered;
}
I cleaned up your function a little bit. "theInput" is a bit vague for a variable name, so I changed it to something more descriptive. I handled the case where the user doesn't enter a number, and I consolidated the document.getElementById and the parseInt into one line. Also, you were mixing types in your original code. You use parseInt (which returns a numeric type), but then you would set theInput to a string. This may not result in an error thanks to JavaScript's flexible type coercion, but it's bad practice regardless.
Now that you have that function, you can modify your SelectImage6 accordingly:
function SelectImage6() {
'use strict';
var div = document.getElementById('outputDiv'); // cached for efficiency
var html = '';
var roll2, imgName2;
var numDice = getNumDice();
for( i=0; i<numDice; i++ ){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
html += '<img alt="die image" src="' + imgName2+'" alt="die" />';
}
div.innerHtml = html;
}
For SelectImage6, I made some changes (in addition to using the value returned by getNumDice). First, you're repeatedly calling getElementById (once, unnecessarily, at the top of the function, then once for every dice rolled!). Any DOM access is expensive, and if you can avoid doing it multiple times, you should. Secondly, you're repeatedly modifying the innerHtml property which, depending on the complexity of your HTML, and your network latency, could cause flicker or other unpleasant effects. What I chose to do instead was to build up the string first, then set it all at once.
In your original function, you were unwittingly using global variables (implied globals) because you didn't declare roll2 and imgName2 as variables. I fixed that, and added use strict to your functions so this mistake will be caught in the future! (My advice is to always set use strict.);
I hope this helps! Welcome to the world of JavaScript.

Javascript - Detecting the first character and alerting the user

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

Categories

Resources