How to avoid repeats after drawing in javascript? - javascript

After clicking on the button "go" one of eight words appears. I was wondering how to write a function which prohibits making repeats, so no word will be shown twice. Any ideas? Thanks for all help :)
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id= "go">go</button>
<div id="word"></div>
<script type="text/javascript">
var words = ["Michael", "Simon", "Peter", "Mark", "Jason", "Paul", "Steve", "George"];
var btn1 = document.getElementById("go");
btn1.addEventListener("click", fill_in);
function getRandomItem(array) {
return array[Math.floor(Math.random() * array.length)]
}
function fill_in(){
var randomWord = getRandomItem(words);
document.getElementById('word').innerHTML += randomWord + " ";
}
</script>
</body>
</html>

You should write method getRandomItem this way.
function getRandomItem(array) {
return array.splice(Math.floor(Math.random() * array.length), 1)[0];
}
Basically, you need to remove the element after displaying it. Fortunately, Array#splice perfectly fits your case since it will both remove the element and return an array containing it.

To avoid repetition, you can remove the words from the array each time it is returned. Lets say getRandomItem returns 'Peter', so remove 'Peter' from the array 'words' before calling getRandomItem again.
To remove the element, you can use below code:
var words = ["Michael", "Simon", "Peter", "Mark", "Jason", "Paul", "Steve", "George"];
var index = words.indexOf("Peter");
if (index > -1) {
words.splice(index, 1);
}

To avoid repetition you should remove the name from the array after it has been displayed on the screen. To remove the name from the array you should find the index of the word, and then remove one item from the array at this index.
To do this you would use the following code
var word = words.indexOf(randomWord);
if(word != -1) {
words.splice(i, 1);
}
You should add this code to your fill_in function and remove the word, after the randomWord has been generated from the array. Once the array is empty you should stop printing to the screen. To check if the array is empty you should check the length of the words array.
function fill_in(){
var randomWord = getRandomItem(words);
var word = words.indexOf(randomWord);
if(word != -1) {
words.splice(i, 1);
}
if(words.length != 0){
document.getElementById('word').innerHTML += randomWord + " ";
}
}
Please see below to see the complete code in action.
var words = ["Michael", "Simon", "Peter", "Mark", "Jason", "Paul", "Steve", "George"];
var btn1 = document.getElementById("go");
btn1.addEventListener("click", fill_in);
function getRandomItem(array) {
return array[Math.floor(Math.random() * array.length)]
}
function fill_in() {
var randomWord = getRandomItem(words);
var i = words.indexOf(randomWord);
if (i != -1) {
words.splice(i, 1);
}
if(words.length != 0) {
document.getElementById('word').innerHTML += randomWord + " ";
}
}
<button id="go">go</button>
<div id="word"></div>

Related

Search for duplicate before adding to list

I'm trying to search for duplicates in a list before adding there any information. Could you please take a look at my code and tell me what I'm doing wrong. Thank you!
Another question is how could I iterate arrayList using Object.entries(arrayList)-loop and get the same result as I got w/o using it? When I tried to use Object.entries I was only able to see 0 [object Object], 1 [object Object] instead of names and genders.
let arrayList = [{
"name": "Brandon",
"gender": "M"
},
{
"name": "Charlotte",
"gender": "F"
},
];
let btn = document.getElementById("btn");
btn.onclick = function() {
let showHere = document.getElementById("showHere");
for (let i = 0; i < arrayList.length; i++) {
let li = document.createElement('li');
let text = `${arrayList[i].name} ${arrayList[i].gender}`;
let insert = document.createTextNode(text);
if (arrayList[i].name.indexOf(li) != -1) {
alert(`${arrayList[i].name} already in list`);
} else {
li.appendChild(insert);
showHere.appendChild(li);
}
console.log(li);
}
}
<button type="button" id="btn">Show list</button>
<ul id="showHere"></ul>
Okay I'm not 100% sure what you intended but, you may consider instead of checking for duplicates, clearing out the array before re-rendering it with new values. I modified your snippet so you can see what I'm talking about.
If you have any questions feel free to make a comment!
[Edit] I added a little snippet to check if a name gender combo already exists before adding it to the list.
let arrayList = [{
"name": "Brandon",
"gender": "M"
},
{
"name": "Charlotte",
"gender": "F"
},
];
let btn = document.getElementById("btn");
const addBtn = document.getElementById('add');
addBtn.onclick = function() {
const name = document.getElementById('name').value;
const gender = document.getElementById('gender').value;
// check if value already exists
if(!arrayList.find(obj => JSON.stringify(obj) === JSON.stringify({name, gender}))){
arrayList.push({
name,
gender
});
} else {
console.log('name gender combo already exists');
}
}
btn.onclick = function() {
let showHere = document.getElementById("showHere");
showHere.innerHTML = '';
for (let i = 0; i < arrayList.length; i++) {
let li = document.createElement('li');
let text = `${arrayList[i].name} ${arrayList[i].gender}`;
let insert = document.createTextNode(text);
if (arrayList[i].name.indexOf(li) != -1) {
alert(`${arrayList[i].name} already in list`);
} else {
li.appendChild(insert);
showHere.appendChild(li);
}
console.log(li);
}
}
<input type="text" id="name" ></input>
<input type="text" id="gender" ></input>
<button type="button" id="add">Add to list</button>
<button type="button" id="btn">Show list</button>
<ul id="showHere"></ul>

Javascript - Compare user input value to randomly generated value

I have a function that displays a random word from an array, in a non-repeated way, and a textbox where the user is supposed to type the same generated word.
I tried using a switch statement to validate the user's answer, comparing his input to the randomly generated word, but it is not working.
My question is, is it even possible to compare such things? And if so, how?
This is my code:
// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];
function randomize() {
if (remainingWords.length === 0) remainingWords = origWords.slice();
const {
length
} = remainingWords;
const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
p.textContent = quote;
}
randomize();
// Validate answer
function submit001() {
var answers = document.getElementById("input001").value.toLowerCase();
switch (answers, remainingWords) {
case "":
text = "Please write something.";
break;
case answers == remainingWords:
text = "Correct.";
randomize();
break;
default:
text = "Wrong.";
}
document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>
An if statement is probably a more appropriate solution to the problem. Try this:
// Generate random, non-repeated word
const p = document.getElementById("randomWord");
const origWords = ["alpha", "bravo", "charlie", "delta", "echo"];
let remainingWords = [];
function randomize() {
if (remainingWords.length === 0) remainingWords = origWords.slice();
const length = remainingWords;
const [quote] = remainingWords.splice(Math.floor(Math.random() * length), 1);
p.textContent = quote;
}
randomize();
// Validate answer
function submit001() {
var answers = document.getElementById("input001").value.toLowerCase();
if (answers == "") {
text = "Please write something.";
} else if (answers == p.textContent) {
text = "Correct.";
randomize();
} else {
text = "Wrong.";
}
document.getElementById("comment").innerHTML = text
}
<input type="text" id="input001" autofocus maxlength="7" spellcheck="false" onKeyDown="if(event.keyCode==13) submit001();">
<p id="randomWord"></p>
<p id="comment"></p>

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

how can i display all items randomly in an array

I want to split a word into letters put it into in array and display the letters randomly. i am having trouble. with words that have double of the same letter. and also the correct amount of letter is being shown but not all the letters are being displayed.
Here is my code I'm a noob:
window.onload = init;
function init() {
//var name=prompt("what is your name ? ","");
//character(name) ;
words();
}
function character(name) {
var name = name;
document.getElementById("words").innerHTML = "hey " + name + " my name is koala could you help me put these words back in order?";
}
function words() {
var lastlet = "";
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = Math.floor(Math.random() * words.length) + 0;
//for one word and seperation with letters
var ranwor = words[rand].split("");
for (var i = 0; i < ranwor.length; i++) {
var inn = ranwor[Math.floor(Math.random() * ranwor.length)].split().shift();
if (true) {
var di = document.getElementById("wor").innerHTML += inn;
}
lastlet = inn;
}
}
#char {
height: 65px;
width: 65px;
}
#words {
height: 100px;
width: 200px;
}
<img id="char" src="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg" />
<p id="words"></p>
<br>
<p id="wor"></p>
<p id="wo"></p>
<br>
<textarea id="inp"></textarea>
<br>
<button>
I think this is right :)
</button>
Just sort the array using a random number and use join() so you do not need to loop.
var words = ["joe", "suzy", "terry", "fox", "lopez"];
var rand = words[Math.floor(Math.random() * words.length)];
function scramble (word, rescrambled) {
var scrambled = word.split("").sort(function(){ return Math.random() > .5 ? 1 : -1; }).join("");
if (word===scrambled && !rescrambled) { //if it matches the original, retry once
return scramble (word, true);
}
return scrambled;
}
console.log("Random word: ", scramble(rand));
console.group("loop them");
while(words.length){
var x = words.pop();
console.log(x,":", scramble(x));
}
console.groupEnd("loop them");

How to use multiple document.getElementById's?

I have a problem with html and js. I don't know why I can only use the first document.getElementById that is on top.
JavaScript.js
var one = "sentence"
document.getElementById("text").innerHTML = one;
var two = "sentence sentence"
document.getElementById("text_2").innerHTML = two;
var three = "sentence sentence sentence"
document.getElementById("text_3").innerHTML = three;
webpage.html
<html>
<head>
</head>
<body>
<div id="text"></div>
</body>
</html>
<script src="test.js"></script>
When using div id="text_2" or div id="text_3", nothing will come up on the output. Only the document.getElementById that is on top in the js file can be seen on the webpage. So I gues i cannot use multiple getElementById's but I don't know a other way yet. What to do?
Thank you
var sentence1 = 'sentence',
sentence2 = 'sentence two',
sentence3 = 'sentence three',
el1 = document.getElementById('text'),
el2 = document.getElementById('text_2'),
el3 = document.getElementById('text_3');
if (el1) {
el1.innerHTML = sentence1;
}
if (el2) {
el2.innerHTML = sentence2;
}
if (el3) {
el3.innerHTML = sentence3;
}
What I want is that sometimes I need just need "text" and another time text_2 and so the same for text_3.
This is easy enough, you just put whichever one you want in a variable that you can pass to getElementById. Something like:
var elementId;
if (conditionForText) {
elementId = "text";
}
else if (conditionForText2) {
elementId = "text_2"
}
else if (conditionForText3) {
elementId = "text_3"
}
// Note: you might want to handle the case where none of the above conditions
// evaluate to true
document.getElementById(elementId).innerHTML = someText
It's not really clear if the element you want to pick is supposed to get the same text or not, but if you have several id's with several different strings that need to be set, you could map them with an object:
var elementsAndStrings = {
text : "sentence one",
text_2 : "sentence two",
text_3 : "sentence three"
};
and now you could do something like:
document.getElementById(elementId).innerHTML = elementsAndStrings[elementId];
HTML
<div class="text">Text1</div>
<div class="text">Text2</div>
<div class="text">Text3</div>
<div class="text">Text4</div>
Javascript
function getElementByClass (className, parent) {
parent || (parent = document);
var descendants= parent.getElementsByTagName('*'), i=-1, e, result=[];
while (e=descendants[++i]) {
((' '+(e['class']||e.className)+' ').indexOf(' '+className+' ') > -1) && result.push(e);
}
return result;
}
texts= getElementByClass("text");
var txtVal="";
for (i = 0; i < texts.length; i++) {
txtVal += texts[i].innerHTML + ", ";
}
alert (txtVal);
DEMO
http://jsfiddle.net/mt78j5m0/
<div id="text_1"></div>
<div id="text_2"></div>
<div id="text_3"></div>
var text = {};
text.text_1 = "One";
text.text_2 = "Two";
text.text_3 = "Three";
var divs = document.querySelectorAll("[id^='text']");
for (var div of divs) {
div.innerHTML = text[div.id];
}
What about:
const elements = [
"id1",
"id2"
].map(document.getElementById);

Categories

Resources