I'm trying to access my random array keys with a radio button on each of them
I want to place the radio button only on the array
of the allQuestions[index].anwsers keys and it has 3 indexes keys.
I'm couldn't make it and this my work so far.
const allQuestions = [{
question: "Which of them is from compton",
anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
correctAnswer: "Kendrick"
},
{
question: "founder of HipHop",
anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
correctAnswer: "Bambata"
},
{
question: "Who won BET Hip Hop Album 2018",
anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
correctAnswer: "Kendrick",
},
{
question: "Best Female HipHop Art 2018",
anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
correctAnswer: "Nicki"
}
]
function render() {
var index, unique;
var print = '<ul>';
for (i = 0; i < allQuestions.length; i++) {
index = Math.floor(Math.random() * allQuestions.length);
}
var showQuiz = document.getElementById('showQuiz');
var showAnswers = document.getElementById('showAnswers');
showQuiz.style.color = 'red';
showQuiz.innerHTML = allQuestions[index].question;
showAnswers.innerHTML = allQuestions[index].anwsers;
// I'm tryin to ue sthe unshift method here but it' not workin
showAnswers.unshift('<input type="radio" value="allQuestions.anwsers[]');
}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>
Appears we are trying to use the Array function unshift() on a DOM element. What i believe you are trying to do is create a list of radio buttons for each answer in your allQuestions.answers[], this can be done with a for loop, or a map like so:
Edit to add answersAsHtml and join(" ") this improves readability and joins each array element with a space instead of the default comma.
const allQuestions = [{
question: "Which of them is from compton",
anwsers: ["Nas", "Tupac", "Omarion", "Kendick"],
correctAnswer: "Kendrick"
},
{
question: "founder of HipHop",
anwsers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
correctAnswer: "Bambata"
},
{
question: "Who won BET Hip Hop Album 2018",
anwsers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
correctAnswer: "Kendrick",
},
{
question: "Best Female HipHop Art 2018",
anwsers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
correctAnswer: "Nicki"
}
]
function render() {
var index, unique;
var print = '<ul>';
for (i = 0; i < allQuestions.length; i++) {
index = Math.floor(Math.random() * allQuestions.length);
}
var showQuiz = document.getElementById('showQuiz');
var showAnswers = document.getElementById('showAnswers');
var answersAsHtml = allQuestions[index].anwsers.map(ans => `<input type="radio" value="${ans}">${ans}</input>`).join(" ");
showQuiz.style.color = 'red';
showQuiz.innerHTML = allQuestions[index].question;
showAnswers.innerHTML = answersAsHtml;
}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>
You are trying to write into an html element, that's not an array. You are probably looking for something more like this.
showAnswers.innerHTML = allQuestions[index].anwsers.map(function (answer){
return '<input type="radio" name="answers" value="' + answer + '"/>' + answer
})
Related
I want to make a website which asks some questions and then will generate 3 random locations based on the users answers. The part I am struggling with is getting the end result to output the locations based on the first question in the object which is:
const questions = [
{
"question": "What area of the world are you thinking of discovering next?",
"answer1": "Europe",
"answer1Array": "europeArray",
"answer2": "Asia",
"answer2Array": "asiaArray",
"answer3": "America",
"answer3Array": "americaArray",
"answer4": "Australasia",
"answer4Array": "australasiaArray"
},
let europeArray1 = ['Algarve - Portugal', 'Asturias and Covadonga - Spain', 'Mdina & Zebbug - Malta']
let asiaArray1 = ['Yakushima Island - Japan', 'Mount Wudang Shan - China', 'Bantayan Island - Philippines'] etc...
I have then created a function to give me back a random location:
let finalEuropeArray1 = europeArray1.sort(function() {
return 0.5 - Math.random();
});
and finally a function to output 3 results
function randomHoliday (array) {
if (array == europeArray1) {
return finalEuropeArray1.slice(europeArray1,3);
} else if (array == americaArray1) {
return finalAmericaArray1.slice(americaArray1,3);
} else if (array == asiaArray1 {
return finalAsiaArray1.slice(asiaArray1,3);
} else {
return finalAustralasiaArray1.slice(australasiaArray1,3);
}
I am able to return 3 separate values with a function calling the first element in each:
let resultA = function seperateArrayA (randomHoliday) {
return `1. ${randomHoliday[0]}`;}
let resultB = function seperateArrayB (randomHoliday) {
return `2. ${randomHoliday[1]}`;}
let resultC = function seperateArrayC (randomHoliday) {
return `3. ${randomHoliday[2]}`;}
but I do not know how to output this in my final .innerHTML based on the first question in the questions object. I can only get it to work by putting in a manual entry e.g. ${resultA(australasiaArray1)}
if(currentQuestion == totalQuestions) {
container.style.display = 'none';
result.innerHTML =
`<h1 class="final-score">Our Top 3 Recommendations:</h1>
<div class="summary">
<p><br></br></p>
<p>${resultA(australasiaArray1)}</p>
<p>${resultB(australasiaArray1)}</p>
<p>${resultC(australasiaArray1)}</p>
</div>
<button class="restart">Restart Quiz</button>
`
};
The setup can be simplified by using nested objects for related answers, checkout the demo below:
const questions = [
{
"question": "What area of the world are you thinking of discovering next?",
"answers": {
"Europe": {
"label": "Europe",
"locations": ['Algarve - Portugal', 'Asturias and Covadonga - Spain', 'Mdina & Zebbug - Malta']
},
"Asia": {
"label": "Asia",
"locations": ['Yakushima Island - Japan', 'Mount Wudang Shan - China', 'Bantayan Island - Philippines']
}
}
}
];
let getRandomLocationForAnswer = function (question, answer) {;
const possibleLocations = question.answers[answer].locations;
const randomIndex = Math.floor((Math.random()*possibleLocations.length));
return possibleLocations[randomIndex];
}
let buildSelect = function(questions){
return questions.map((question, index) => {
const possibleAnswers = Object.keys(question.answers);
return`<select class="question" data-question-index="${index}">${possibleAnswers.map(l => `<option value="${l}">${l}</option>`)}</select>`;
}).join('');
}
let showResults = function(questions, questionIndex, answer){
const question = questions[questionIndex];
document.querySelector('#results').innerHTML =
`<h1 class="final-score">Our Top 3 Recommendations:</h1>
<div class="summary">
<p><br></br></p>
<p>${getRandomLocationForAnswer(question, answer)}</p>
<p>${getRandomLocationForAnswer(question, answer)}</p>
<p>${getRandomLocationForAnswer(question, answer)}</p>
</div>
<button class="restart">Restart Quiz</button>
`
}
document.querySelector('#questions').innerHTML += buildSelect(questions);
document.querySelectorAll('.question').forEach(question => {
question.addEventListener('change', e => {
const select = e.currentTarget;
showResults(questions, parseInt(select.dataset.questionIndex), select.value);
});
});
<section id="questions">
</section>
<section id="results">
</section>
resultA, resultB, resultC are functions, not values. if you put them in the template you will get a function reference and not the result of the function. To get the result you need to call the function(which you do in the last code snippet).
in order to get it to work simply define variables and set them to the function result:
if(currentQuestion == totalQuestions) {
container.style.display = 'none';
var l_resultA = resultA(australasiaArray1)
...
result.innerHTML =
`<h1 class="final-score">Our Top 3 Recommendations:</h1>
<div class="summary">
<p><br></br></p>
<p>${l_resultA}</p>
....
</div>
<button class="restart">Restart Quiz</button>`
};
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 5 years ago.
Apologies if my question title is not accurate, I couldn't think how to phrase it.
var options = [2,3,4]
// select drop down
var select = document.getElementById("itemSet");
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.text = opt;
el.value = opt;
select.add(el);
}
// define arrays
var arrActivity = ["alien monster", "man in business suit levitating", "fencer", "horse racing", "skier", "snowboarder", "golfer", "surfer", "rowboat", "swimmer"];
var arrFood = ["grapes", "melon", "watermelon", "tangerine", "lemon", "banana", "pineapple", "red apple", "green apple", "pear"];
var arrObjects = ["skull and crossbones", "love letter", "bomb", "hole", "shopping bags", "prayer beads", "gem stone", "hocho", "amphora", "world map"];
var arrLetters = ["letter a", "letter b", "letter c", "letter d", "letter e", "letter f", "letter g", "letter h", "letter i", "letter j"];
// format the array data for output into the textarea
function boom() {
var e = document.getElementById("itemSet");
var myCols = e.options[e.selectedIndex].value;
console.log(myCols);
var arrNew = [];
if (document.getElementById("radioActivity").checked) {
y = arrActivity;
} else if (document.getElementById("radioFood").checked) {
y = arrFood;
} else if (document.getElementById("radioObjects").checked) {
y = arrObjects;
} else if (document.getElementById("radioLetters").checked) {
y = arrLetters;
}
for (var i = 0; i < y.length; i += myCols) {
arrNew.push(
y.slice(i, i + myCols)
);
}
// set the textarea output
op = JSON.stringify(arrNew, null, 4);
document.getElementById('output').value = op;
}
<form onSubmit="return false;">
<label class="radio-inline">
<input type="radio" name="myArray" id="radioActivity" value="valActivity"> Activity
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioFood" value="arrFood"> Food
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioObjects" value="arrObjects"> Objects
</label>
<label class="radio-inline">
<input type="radio" name="myArray" id="radioLetters" value="arrLetters"> Letters
</label>
<select class="form-control" id="itemSet" name="itemSet"></select>
<button onClick="boom();"> Check Radio </button>
<textarea id="output" class="form-control" style="width:95%; height:500px; margin-top:20px;"></textarea>
</form>
When I click the "Check Radio" button, I want to reformat the arrays into chunks using this for loop:
for (var i = 0; i < y.length; i+=myCols) {
arrNew.push(
y.slice(i, i+myCols)
);
}
If I submit the form with a select value of e.g. 2 then the array is reformatted as:
[
[
"alien monster",
"man in business suit levitating"
],
[
"fencer",
"horse racing",
"skier",
"snowboarder",
"golfer",
"surfer",
"rowboat",
"swimmer"
]
]
Instead of in chunks of 2:
[
[
"alien monster",
"man in business suit levitating"
],
[
"fencer",
"horse racing"
],
[
"skier",
"snowboarder"
],
[
"golfer",
"surfer"
],
[
"rowboat",
"swimmer"
]
]
This CodePen demonstrates the issue: https://codepen.io/paperknees/pen/boXjXW
I can't work out what I'm doing wrong.
myCols is a string, therefore
y = 0;
myCols = "2"
//first iteration
y += myCols // "2"
//second iteration:
y += myCols // "22"
To solve this, add an unary plus operator:
var myCols = +e.options[e.selectedIndex].value;
You'll get it here -
while (y.length > 0)
arrNew.push(y.splice(0, myCols))
console.log(arrNew);
That's it!
Once again, I need your input on the problem that I am having now.
I am creating a MCQ trivia where I encounter a logic problem.
Although for this example, I purposely set the answer are B, C or D, the result div will always show the result is correct – although I only set an event listener on button A but no answer.
Based on my code below, am I comparing the element value with the array answer value the right way?
var exam=[{
"question": "Q1?",
"option": ["A","B","C","D"],
"answer": "B"
},{
"question": "Q2?",
"option": ["A","B","C","D"],
"answer": "C"
},{
"question": "Q3?",
"option": ["A","B","C","D"],
"answer": "D"
},{
"question": "Q4?",
"option": ["A","B","C","D"],
"answer": "B"
},{
"question": "Q5?",
"option": ["A","B","C","D"],
"answer": "C"
}]
//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');
//display question and answer
function displayQues() {
//select one question randomly from the quiz array
var i = Math.floor(Math.random() * exam.length);
questionEl.textContent=exam[i].question;
opt1.textContent = exam[i].option[0];
opt2.textContent = exam[i].option[1];
opt3.textContent = exam[i].option[2];
opt4.textContent = exam[i].option[3];
};
//load this when page load
displayQues();
opta.addEventListener("click", function() {
if (opt1.value === exam.answer) {
displayQues();
resultCont.textContent = "Correct!";
} else {
resultCont.textContent = "Incorrect!";
}
});
<div id="container">
<div class="title"> Alan Koh Exam Question</div>
<div id="question"> </div>
<button id="opta"> A: <span id="opt1"></span> </button>
<button id="optb"> B: <span id="opt2"></span> </button>
<button id="optc"> C: <span id="opt3"></span> </button>
<button id="optd"> D: <span id="opt4"></span> </button>
<div id="result"></div>
The problem with your current code is opt1.value === exam.answer. Both these properties are undefined. opt1.value because it's not set (I believe you want opt1.textContent) and exam.answer because exam is an array. You get Correct! always since undefined === undefined is true
Your issue can be solved by returning the current displayed question and using it for comparison.
var exam = [{
"question": "Q1?",
"option": ["A", "B", "C", "D"],
"answer": "B"
}, {
"question": "Q2?",
"option": ["A", "B", "C", "D"],
"answer": "C"
}, {
"question": "Q3?",
"option": ["A", "B", "C", "D"],
"answer": "D"
}, {
"question": "Q4?",
"option": ["A", "B", "C", "D"],
"answer": "B"
}, {
"question": "Q5?",
"option": ["A", "B", "C", "D"],
"answer": "C"
}]
//
//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
//
var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');
//display question and answer
function displayQues() {
//select one question randomly from the quiz array
var i = Math.floor(Math.random() * exam.length);
questionEl.textContent = exam[i].question;
opt1.textContent = exam[i].option[0];
opt2.textContent = exam[i].option[1];
opt3.textContent = exam[i].option[2];
opt4.textContent = exam[i].option[3];
return exam[i]; // Return the chosen exam variable
};
//load this when page load
var currentExam = displayQues(); // Store the chosen exam
opta.addEventListener("click", function() {
if (opt1.textContent === currentExam.answer) {
currentExam = displayQues(); // Store the new question
resultCont.textContent = "Correct!";
} else {
resultCont.textContent = "Incorrect!";
}
});
<div id="container">
<div class="title"> Alan Koh Exam Question</div>
<div id="question"> </div>
<button id="opta"> A: <span id="opt1"></span> </button>
<button id="optb"> B: <span id="opt2"></span> </button>
<button id="optc"> C: <span id="opt3"></span> </button>
<button id="optd"> D: <span id="opt4"></span> </button>
<div id="result"></div>
Here is the jsfiddle link with the corrected code.
You have to loop through exam and compare the correct question and answer.
var allQuestions = [{
question1: "What is 1 + 1?",
choices: ["1", "2", "3", 4],
correctAnswer: ["2"]
}, {
question2: "What is 2 + 2?",
choices: ["6", "2", "3", 4, ],
correctAnswer: ["4"]
}, {
question3: "What is 3 + 3?",
choices: ["3", "6", "9", 12],
correctAnswer: ["6"]
}];
var newArray = shuffleArray(allQuestions);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function appendQuestions(number) {
if (newArray == "undefined" || newArray == "null" || newArray.length == 0) {
document.getElementById("questionForm").innerHTML = "Complete!";
} else {
for (i = 0; i < 4; i++) {
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>")
}
}
}
$(function() {
$("#questionList").empty();
appendQuestions();
newArray.shift();
})
function isCorrectAnswer() {
checkedVal = $("input[type=radio][name=question]:checked").val();
if (checkedVal == newArray[0].correctAnswer) {
alert("Correct!");
} else {
alert("Wrong!");
}
alert(checkedVal);
}
$("#submitButton").click(function() {
isCorrectAnswer();
$("#questionForm").empty();
appendQuestions();
newArray.shift();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<section id='questions'>
<form id="questionForm">
</form>
<div style='clear:both'></div>
<input id='submitButton' type='button' value='Submit'>
</section>
</div>
First off, sorry for the amount of code pasted. I have no idea if I'm missing some small bug or if I'm just writing the wrong code, so I figured it would be best to post all of it.
I am trying to get the value of a radio button. In the isCorrectAnswer function the first 2 lines are to determine the value of the radio button that is currently checked. The problem is when I alert the value of the radio button, it just says "on". I have searched for the last hour trying to figure out what this means or how to fix it and could not find a thing.
I apologize if this is a stupid question or if it has already been answered.
You have to change this line :
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>");
To :
$("#questionForm").append("<input name='question' type='radio' value='" +
JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));
Hope this helps.
I need to make an object oriented pirate translator in javascript for my final, I have an idea and have some code but can't get it to output correctly on my page. I have it set up so you type the english phrase in one box and then in the other box it spits out the pirate version. I will not step through my array of objects. I will post code. Thanks for any help I can get!!!
var $ = function(id) { return document.getElementById(id); }
var Dictionary = [{
Greetings: {
hello:"ahoy",
hi:"yohoho",
pardon_me:"avast",
excuse_me:"arrr"
},
People: {
stranger:"scurvy",
sir:"matey",
madam:"proud beauty",
miss:"comely wench",
officer:"foul blaggart",
enemy:"scallywag"
},
Questions: {
where_is:"whar be",
can_you_help_me_find:"know ye",
is_that:"be that",
how_far_is_it_to:"how many leagues to"
},
Articles: {
the:"th",
a:"a briny",
any:"some godforsaken",
nearby:"broadside",
my:"me",
your:"yer"
},
Adjectives: {
old:"barnacle-covered",
attractive:"comely",
happy:"grog-filled"
},
Places: {
restroom:"head",
restaurant:"galley",
hotel:"fleabag inn",
mall:"market",
pub:"Skull & Scuppers",
bank:"buried trasure"
},
Desires: {
I_would_like_to:"I be needin to",
I_desire:"I have a fierce fire in me belly",
I_wish_I_knew_how_to:"I be hankerin to",
my_mother_told_me_to:"me dear ol mum, bless her black soul, tol me to",
my_companion_would_like_to:"me mate, ol Rumpot, wants to"
},
Actions: {
find:"come across",
take_a_nap:"have a bit of a lie down",
make_a_withdrawal:"seize all yer doubloons",
have_a_cocktail:"swill a pint or two of grog",
kill_him:"blow the man down",
frown:"hang the jib",
take_a_hike:"walk the plank"
},
}];
function Translate(text)
// Returns: a copy of text with English phrases replaced by piratey equivalents
{
for (var i = 0; i < Dictionary.length; i++) {
var toReplace = new RegExp("\\b"+Dictionary[i][0]+"\\b", "i");
var index = text.search(toReplace);
while (index != -1) {
text = text.replace(toReplace, Dictionary[x][y]);
index = text.search(toReplace);
}
}
text = text.replace(/\./g, function() {
return Math.random() < 0.5 ? ". arrrrrrrrr" : "."
});
return text.charAt(0).toUpperCase() + text.substring(1);
}
var clear_click = function() {
$("output1").value = "";
$("output2").value = "";
}
window.onload = function() {
$("clear").onclick = clear_click;
}
/*for (var x in Dictionary) {
for (var y in Dictionary[x])
console.log (y, Dictionary[x][y]);
}*/
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Pirate Translator </title>
<script src="js/test2.js"></script>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/styles.css"/>
</head>
<body>
<h1>Jacob's Pirate Translator</h1>
<p>Simply click on the buttons to translate<br />
words and/or phrases from English to pirate talk.
<hr />
<form name="TalkForm">
<table>
<tr><td align="center"><b>English</b>
<td>
<td align="center"><b>Pirate</b>
<tr><td><textarea name="English" id="output1" rows=12 cols=35 wrap="virtual"></textarea> </td>
<td align="center"> <br />
<input type="button" value="Translate --->"
onclick="document.TalkForm.Pirate.value =
Translate(document.TalkForm.English.value);"> </td>
<td><textarea name="Pirate" id="output2" rows=12 cols=35 wrap="virtual"></textarea> </td>
<input type="button" id="clear" value="clear">
</tr>
</table>
</form>
</body>
</html>
EDIT2: I've modified your Dictionary. If you follow the format of my Dictionary you can go as deep of arrays as you want. It should work. I've tested with your examples in all different kinds of orders and with text not found in the dictionary. Feel free to try it out.
And to add to the challenge, I made recursive functions. :D No for/while loops.
DEMO
var Dictionary = {
hello: "ahoy",
hi: "yohoho",
pardon: [1, {
me: "avast"
}],
excuse: [1, {
me: "arrr"
}],
stranger: "scurvy",
sir: "matey",
madam: "proud beauty",
miss: "comely wench",
officer: "foul blaggart",
enemy: "scallywag",
where: [1, {
is: "whar be"
}],
can: [4, {
you_help_me_find: "know ye"
}],
is: [1, {
that: "be that"
}],
how: [4, {
far_is_it_to: "how many leagues to"
}],
the: "th",
a: "a briny",
any: "some godforsaken",
nearby: "broadside",
my: "me",
your: "yer",
old: "barnacle-covered",
attractive: "comely",
happy: "grog-filled",
restroom: "head",
restaurant: "galley",
hotel: "fleabag inn",
mall: "market",
pub: "Skull & Scuppers",
bank: "buried trasure",
would: [1, {
like: "be needin"
}],
I: [
[1, {
desire: "I have a fierce fire in me belly"
}],
[5, {
wish_I_knew_how_to: "I be hankerin to"
}]
],
my: [
[4, {
mother_told_me_to: "me dear ol mum, bless her black soul, tol me to"
}],
[4, {
companion_would_like_to: "me mate, ol Rumpot, wants to"
}]
],
find: "come across",
take: [2, {
a_nap: "have a bit of a lie down"
}],
make: [2, {
a_withdrawal: "seize all yer doubloons"
}],
have: [2, {
a_cocktail: "swill a pint or two of grog"
}],
kill: [1, {
him: "blow the man down"
}],
frown: "hang the jib",
take: [2, {
a_hike: "walk the plank"
}]
};
function translate(text) {
var hop = 1;
var textToReturn = "";
//checking if the text is already split, if not we split
if (typeof text === 'string') {
text = text.split(' ');
}
if (text.length > 0) {
if (typeof Dictionary[text[0]] == 'undefined' || typeof Dictionary[text[0]] === 'string') {
textToReturn = (Dictionary[text[0]] || text[0]);
text = text.slice(hop, text.length);
} else {
var info = recursiveCheck(text, Dictionary[text[0]]);
textToReturn = (info.hop == 1) ? text[0] : info.text;
text = text.splice(info.hop, text.length);
}
if(text.length > 0)
{
textToReturn += ' ' + translate(text);
}
}
return textToReturn;
}
function recursiveCheck(text, arr)
{
var found = {hop:1, text: ''};
if(arr.length > 0)
{
if(typeof parseInt(arr[0]) === 'number' && text.length-1 >= arr[0])
{
var phrase = text.slice(1, arr[0]+1);
if(arr[1][phrase.join('_')])
{
found.hop = arr[0]+1;
found.text = arr[1][phrase.join('_')];
}
}
else
{
found = recursiveCheck(text, arr[0] || []);
if(found.hop == 1 && arr.length > 1)
{
found = recursiveCheck(text, arr.slice(1, arr.length));
}
}
}
return found;
}
var tra = document.getElementById('translate');
var pir = document.getElementById('pirate');
pir.disabled = true;
var eng = document.getElementById('english');
eng.onkeyup = function(){
pir.value = "";
}
tra.onclick = function () {
pir.value = translate(eng.value);
};
HERE is an example of a deep array if you want to go further with the dictionary:
...
I: [
[1, {
desire: [
[1,{ a: "I have a fierce fire in me belly"}],
[1,{ one: "I have one fierce fire in me belly"}]
}],
[5, {
wish_I_knew_how_to: "I be hankerin to"
}]
],
...
Of course I haven't tried it yet, but you can if you actually need it to work. Good luck.
EDIT: The point of this code is to show how to access your list. You don't seem to be using categories in your code, so why have them?
Your list looks a bit complex for a simple translation. Last I checked, dictionaries don't have categories.. Joke aside I've simplified your list.
var Dictionary = {
hello:"ahoy",
hi:"yohoho",
pardon_me:"avast",
excuse_me:"arrr",
stranger:"scurvy",
sir:"matey",
madam:"proud beauty",
miss:"comely wench",
officer:"foul blaggart",
enemy:"scallywag",
where_is:"whar be",
can_you_help_me_find:"know ye",
is_that:"be that",
how_far_is_it_to:"how many leagues to",
the:"th",
a:"a briny",
any:"some godforsaken",
nearby:"broadside",
my:"me",
your:"yer",
old:"barnacle-covered",
attractive:"comely",
happy:"grog-filled",
restroom:"head",
restaurant:"galley",
hotel:"fleabag inn",
mall:"market",
pub:"Skull & Scuppers",
bank:"buried trasure",
I_would_like_to:"I be needin to",
I_desire:"I have a fierce fire in me belly",
I_wish_I_knew_how_to:"I be hankerin to",
my_mother_told_me_to:"me dear ol mum, bless her black soul, tol me to",
my_companion_would_like_to:"me mate, ol Rumpot, wants to",
find:"come across",
take_a_nap:"have a bit of a lie down",
make_a_withdrawal:"seize all yer doubloons",
have_a_cocktail:"swill a pint or two of grog",
kill_him:"blow the man down",
frown:"hang the jib",
take_a_hike:"walk the plank"
};
function translate(text)
{
pir.value = Dictionary[text.split(' ').join('_')] || 'not found';
}
var tra = document.getElementById('translate');
var pir = document.getElementById('pirate');
pir.disabled = true;
var eng = document.getElementById('english');
tra.onclick = function(){ translate(eng.value) };
html:
<input id="english" type="text" placeholder="english"/>
<input id="pirate" placeholder="pirate"/>
<button id="translate">Translate</button>
I've simplified the code (by a lot) so I could get a simple working model.
Working jsfiddle: http://jsfiddle.net/Grimbode/f296h/2/