Search for duplicate before adding to list - javascript

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>

Related

Get Elements of a HTML div

i am building a configuration utility and having a problem with the js.
I am very new to javascript so i apologize in advance for the request for help.
in my HTML i have multiple divs that are structured like this:
<div id="options" class="opt">
<h2 id="optionName">Power Button Options</h2>
<label for="pwrAvl">Power Button Available</label>
<input type="checkbox" name="pwrAvl" id="pwrAvl"/ >
<br /><br />
<label for="pwrLabel">Power Button Label</label>
<input type="text" name="pwrLabel" id="pwrLabel"/ >
<br /><br />
<label for="pwrGraphic">Power Button Graphic</label>
<select name="pwrGraphic" id="pwrGraphic">
<option value="" selected>
----- Please select a graphic -----
</option>
<option value="power.jpeg">Power</option>
<option value="light.jpg">Light</option>
<option value="help.jpg">Help</option>
<option value="camera.jpg">Camera</option>
</select>
<br /><br />
<label for="pwrIndex">Power Button Menu Index</label>
<input type="text" name="pwrIndex" id="pwrIndex"/ >
</div>
i have between 5-10 divs that will all be structured the same way just with different labels and input values.
i tried adding all the divs to an array and then enumerate through the array but that did not work.
here is my js file what i have tried:
{
const bar = document.querySelector('options');
var opts = document.querySelectorAll('.opt')
var option = {}
var nCount = $(".opt").length;
var divArray = [];
var optName = document.getElementById('optionName');
function addArray() {
for (let i = 0; i < nCount; i++) {
divArray[i] = opts[i];
}
}
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration": {
"Options": [],
}
}
addArray()
console.log(`Divarray = ${divArray.length}`)
//The following would never work
opts.forEach(label => {
$('[id=optionName]').each(function () {
var atId = this.id;
console.log(`Searched Name = ${atId.innerHTML}`)
});
});
divArray.forEach(element => {
var name = divArray.getElementById('optionName').innerHTML;
console.log(name)
option = new SystemOptions(name, "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
});
for (let i = 0; i < nCount; i++) {
// console.log(` ${$(".opt").find("h2[id=optionName").each.text()}`)
console.log(` ${divArray[i].querySelector(optName[i]).innerHTML}`)
}
// i did this once to see if the SystemsOptions function worked
// obviosly it added the same data 7 times but i was trying to be sure the function worked and created the json objects
for (let i = 1; i < nCount; i++) {
option = new SystemOptions("Power", "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
}
let data = JSON.stringify(info, 0, 4);
console.log(data);
}
}
any help would be greatly appreciated.
not the most eloquent but this does work.
sure there are better ways:
var opts = document.querySelectorAll('.opt');
var option = {};
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration" :{
"Options": [],
}
};
for(var opt of opts)
{
var name = opt.getElementsByTagName('h2')[0].innerHTML;
let isAvailable = opt.getElementsByTagName("input")[0].value;
let optLabel = opt.getElementsByTagName("input")[1].value;
let optGraphic = opt.getElementsByTagName('select')[0].value;
let index = opt.getElementsByTagName("input")[2].value;
option = new SystemOptions(name, isAvailable, optLabel, optGraphic, index);
info.SystemConfiguration.Options.push(option);
}
console.log(`Number of options = ${opts.length}`)
let data = JSON.stringify(info, 0, 4);
console.log(data);
};

How to populate multiple HTML DOM elements with local storage values

I want to display contents in the last <div> element when a click event occurs but now it only shows 1st 2 elements. Is there something I am not doing right somewhere?
Here is my code so far:
JS
const iname = document.getElementById("name");
const iemail = document.getElementById("email");
const iphone = document.getElementById("phone");
const submit = document.getElementById("submit");
const storage = document.getElementById("storage");
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
localStorage.setItem(name, "");
localStorage.setItem(email, "");
localStorage.setItem(phoneno, "");
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `Name : ${key}<br />Email : ${value}`;
}
localStorage.clear()
HTML
<p>Name</p>
<input id="name" autocomplete="off">
<p>Email</p>
<input id="email" autocomplete="off">
<p>Phone no</p>
<input id="phone" autocomplete="off">
<button id="submit">Let's go</button>
<div id="storage" class="box">
<h1>Is this correct?</h1></div>
I think you are setting the values in localstorage the wrong way.
The syntax for storing stuff in there is localstorage.setItem(keyName, keyValue).
And your code is setting the keyName argument to the value you are getting from the form and keyValue argument to an empty string; not what you need.
Make the following changes and you should be good to go (see comments):
submit.onclick = function () {
const name = iname.value;
const email = iemail.value;
const phoneno = iphone.value;
if (name && email && phoneno) {
// set local storage values
localStorage.setItem("name", name); // modified
localStorage.setItem("email", email); // modified
localStorage.setItem("phoneno", phoneno); // modified
location.reload();
}
console.log(localStorage); // new (maybe unnecessary)
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
storage.innerHTML += `${upFirst(key)}: ${value}<br>`; // modified
}
localStorage.clear();
/**
* new: making the first letter an upper case (for labels in the output div).
* See usage in 'for loop' above.
*/
function upFirst(stringValue) {
return stringValue.slice(0, 1).toUpperCase() + stringValue.slice(1);
}

How to use buttons values and objects values in a if statement to check correct answers (doing a quiz)

I can't compare the value from the Object with the value from the buttons.
I'm going you the complete code so you can understand what I did.
let preguntas = [{
Pregunta: "En qué año salió salió Borderlands 2",
Respuestas: [
2012,
2010,
2011,
2013
],
Respuesta: 2012,
}, {
Pregunta: "Cuál de estos Quake va a salir remasterizado",
Respuestas: [
"Quake 1",
"Quake 2",
"Quake 3",
"Quake 4"
],
Respuesta: "Quake 2"
}];
let numeroPregunta = 0;
// Functions that shows question and correct answer
const pasarPregunta = function() { // Funciona sin pasarRespuesta();
let titulo = document.getElementsByClassName("titulo-pregunta");
titulo[0].innerHTML = preguntas[numeroPregunta].Pregunta;
pasarRespuesta();
cambiarValue();
numeroPregunta++;
progressBar();
}
// SHOWS NEXT QUESTION
const pasarRespuesta = function() {
let listaPreguntas = document.getElementsByClassName("lista-preguntas");
for (let i = 0; i < preguntas[numeroPregunta].Respuestas.length; i++) {
listaPreguntas[i].innerHTML = preguntas[numeroPregunta].Respuestas[i];
}
}
// CHANGES VALUES FROM BUTTONS
const cambiarValue = function() {
let value = document.getElementsByClassName("value");
for (let i = 0; i < preguntas[numeroPregunta].Respuestas.length; i++) {
value[i].value = preguntas[numeroPregunta].Respuestas[i];
value[i].onclick = function() {
comprobarRespuestas(value[i].value);
}
}
}
// CHECKS QUESTION AND ANSWER
const comprobarRespuestas = function() {
let opcionSeleccionada = document.querySelector("button[type=submit]");
let respuesta = opcionSeleccionada.value;
if (preguntas[0].Respuesta == respuesta) {
alert("Bien");
} else {
alert("No!")
}
}
<button name="subject" type="submit" value="valor" class="lista-preguntas value"></button>
<button name="subject" type="submit" value="valor" class="lista-preguntas value"></button>
<button name="subject" type="submit" value="valor" class="lista-preguntas value"></button>
<button name="subject" type="submit" value="valor" class="lista-preguntas value"></button>
I don't know how to write the "comprobarRespuestas();" function. I need to compare de value from the object inside the array with the values from the buttons that are going to change thanks to javascript
you can do like this fiddle,
const cambiarValue = function() {
let value = document.getElementsByClassName("value");
for (let i = 0; i < preguntas[numeroPregunta].Respuestas.length; i++) {
value[i].value = preguntas[numeroPregunta].Respuestas[i];
value[i].onclick = function(e) {
comprobarRespuestas(e.target.value);
}
}
}
const comprobarRespuestas = function(val) {
//making -1 to get the current index because already increased above function
if (preguntas[numeroPregunta - 1].Respuesta == val) {
alert("Bien");
} else {
alert("No!")
}
}

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>

Matching radio button selection with nested Array content in Javascript

UPDATE 6-25-2014
Any insight would be appreciated!
UPDATE 6-21-2014
I tried to make the radio variables, global so the 'if block' in the 'answerFwd' function could be compared to the correctAnswer Array, but that didn't work!
UPDATE 6-16-2014
ADDED JS FIDDLE
I am building a quiz and creating an array of radio buttons dynamically, and would like to match the selected button with the correct answer I have established in the question array.
html
<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Observers</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">The Watchers </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">The Sentinels</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Oa</div>
</div>
questions:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0 }, {
"question": "What is the name of Darth Vader's flag ship?",
"choices": ["The Avenger", "Devastator ", "Conquest", "The Executor"],
"correctAnswer": 3 },{},{} //other questions];
var item = allQuestions[0];
var currentQuestion = 0;
var playersScore = 0;
//function which creates the buttons
function createRadioButtonFromArray(array) {
var len = array.length;
var responses = document.getElementById("responses");
responses.innerHTML = '';
for (var i = 0; i < len; i++) {
radio = document.createElement("input"); //Updated 6-21-2014 removed 'var'
radio.type = "radio";
radio.name = "choices";
radio.className = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
ar radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.className = "choiceText";
radioText.innerHTML = array[i];
responses.appendChild(radio);
responses.appendChild(radioText);
}
}
function answerFwd() {
var answerOutput = " ";
var itemAnswers = allQuestions;
var playerTally = 0; //Updated 6-9-2014
var playerFeedback = " "; //Updated 6-9-2014
var playerMessage = document.getElementById("playerMessage"); //Updated 6-9-2014
if (currentAnswer <= itemAnswers.length) {
currentAnswer++;
}
createRadioButtonFromArray(itemAnswers[currentQuestion].choices);
* Updated 6-9-2014 I am stumped; This doesn't work but I was encouraged I got a score tally on the page! Am I comparing the elements correctly? Updated 6-21-2014 This reversed the gain, where I had the tally render on the screen*
if (itemAnswers.correctAnswer === responses.id) { //Updated 6-21-2014
playerTally += 1;
playerFeedback += "<h5>" + playerTally + "</h5> <br/>";
playerMessage.innerHTML = playerFeedback;
}
}
At first I tried to debug this but had trouble finding where the error was coming from.
One thing I noticed was currentAnswer variable was only being set once. (when it was declared)
Another thing that would make this cleaner is storing each response to each question as a property of the questions object.
For example: {"question": "What is the registry of the Starship Reliant?","choices": ["NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],"correctAnswer": 1,"selectedAnswer": 0}
This is a good example of why you may want to use object oriented programming. You can keep the global namespace clean, while also having tighter control over your variables.
I put together this Quiz Code using some object oriented principles:
JavaScript
var Quiz = function(questions) {
this.questions = questions;
this.$template = {
"header": document.querySelector(".question"),
"options": document.querySelector(".question-choices")
};
this.init();
}
Quiz.prototype = {
"init": function() {
this.question = 0;
this.generateQuestion();
this.bindEvents();
},
//gets called when this.question == this.questions.length, calculates a score percentage and alerts it
"score": function() {
var correctCount = 0;
this.questions.forEach(function(question){
if ( (question.selectedAnswer || -1) === question.correctAnswer ) correctCount += 1
})
alert("Score: " + ((correctCount / this.questions.length) * 100) + "%")
},
//Gets called during initialization, and also after a nav button is pressed, loads the question and shows the choices
"generateQuestion": function() {
var question = this.questions[this.question];
this.$template.header.innerHTML = question.question;
this.$template.options.innerHTML = "";
question.choices.forEach(this.createRadio.bind(this));
},
//Binds the previous, and next event handlers, to navigate through the questions
"bindEvents": function() {
var _this = this,
$nextBtn = document.querySelector(".question-navigation--next"),
$prevBtn = document.querySelector(".question-navigation--prev");
$nextBtn.addEventListener("click", function(e) {
//Go to the next question
_this.question++;
if ( _this.question == _this.questions.length ) {
_this.score();
} else {
_this.generateQuestion();
}
});
$prevBtn.addEventListener("click", function(e) {
_this.question--;
if ( _this.question <= 0 ) _this.question = 0
_this.generateQuestion();
});
},
//Create each individual radio button, is callback in a forEach loop
"createRadio": function(choice, index) {
var question = this.questions[this.question];
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "options";
radio.id = "option-"+index;
if ( question.selectedAnswer === index ) {
radio.checked = true;
}
radio.addEventListener("click", function(e) {
question.selectedAnswer = index;
})
var radioText = document.createElement("label");
radioText.setAttribute("for", "option-"+index)
radioText.innerHTML = choice;
radioText.insertBefore(radio, radioText.firstChild);
this.$template.options.appendChild(radioText);
}
}
var q = new Quiz(allQuestions)

Categories

Resources