I'm creating a quiz that requires every answer to be answered. The problem is that you should be able to skip questions if you don't have an answer. I'm trying to set a default answer everytime I press next so when I try to skip one I don't have to answer for it to have a value. The default value I want is each time the last value of my array.
next and previous question
SetQuestion(question) {
if (this.questionNumber >= 0) {
let oldAnswerButton = document.querySelectorAll('.filter_anwser');
// Deletes old question when the next question is clicked
for (let answerButton of oldAnswerButton) {
answerButton.style.display = 'none';
}
}
this.questionNumber = question;
let q = this.quiz[question];
// Check if your at the last question so the next button will stop being displayed.
if (this.questionNumber === Quiz.length - 1) {
this.nextbtn.style.display = 'none';
this.prevbtn.style.display = 'block';
this.resultbtn.style.display = 'grid';
} else if (this.questionNumber === 0) {
this.nextbtn.style.display = 'block';
this.prevbtn.style.display = 'none';
this.resultbtn.style.display = 'none';
} else {
this.nextbtn.style.display = 'block';
this.prevbtn.style.display = 'block';
this.resultbtn.style.display = 'none';
}
// Displays Question
this.questionName.textContent = q.questionText;
this.questionName.id = "questionID";
return q;
console.log(this.getLink())
console.log(this.tmp)
}
IntoArray() {
const UrlVar = new URLSearchParams(this.getLink())
this.UrlArray = [...UrlVar.entries()].map(([key, values]) => (
{[key]: values.split(",")}
)
);
}
NextQuestion() {
// let quizUrl = this.url[this.questionNumber];
let question = this.SetQuestion(this.questionNumber + 1);
let pre = question.prefix;
let prefixEqual = pre.replace('=', '');
let UrlArr = this.UrlArray;
let UrlKeys = UrlArr.flatMap(Object.keys)
let answers = question.chosenAnswer.slice(0, -1);
this.clicked = true;
// Displays answers of the questions
for (let y = 0; y < answers.length; y++) {
let item = answers[y];
// Display answer buttons
if (UrlKeys.includes(prefixEqual)) {
console.log("exists");
let btn = document.querySelector('button[value="' + item.id + '"]');
btn.style.display = 'block';
} else {
let btn = document.createElement('button');
btn.value = item.id;
btn.classList.add("filter_anwser", pre)
btn.id = 'answerbtn';
btn.textContent = item.name;
this.button.appendChild(btn);
}
// let quizUrl = control.url[control.questionNumber];
// // console.log(this.tmp);
// if (quizUrl === undefined) {
// quizUrl.push(question.prefix[y] + '');
// }
// if (quizUrl === undefined){
// this.tmp.push('');
// }
}
this.IntoArray();
}
PrevQuestion() {
let question = this.SetQuestion(this.questionNumber - 1);
let answers = question.chosenAnswer.slice(0, -1);
// Displays answers of the questions
for (let y = 0; y < answers.length; y++) {
let item = answers[y];
// Display answer buttons
let btn = document.querySelector('button[value="' + item.id + '"]');
btn.style.display = 'block';
}
this.IntoArray();
}
Link creator:
/**
* Returns the parameters for the URL.
*
* #returns {string}
*/
getLink() {
this.tmp = [];
for (let i = 0; i < this.url.length; i++) {
// Check if question is from the same quiz part and adds a , between chosen answers and add the right prefix at the beginning
if (this.url[i].length > 0) {
this.tmp.push("" + Quiz[i].prefix + this.url[i].join(","))
// console.log(this.url)
}
if (this.url[i].length === 0) {
this.tmp.push("");
}
}
/// If answers are from different quiz parts add a & between answers.
return "" + this.tmp.join("&");
// console.log(this.url[i].prefix);
};
Answer click event
control.button.addEventListener("click", function (e) {
const tgt = e.target;
control.clicked = true;
// clear the url array if there's nothing clicked
if (control.url.length === control.questionNumber) {
control.url.push([]);
}
let quizUrl = control.url[control.questionNumber];
// Check if a button is clicked. Changes color and adds value to the url array.
if (quizUrl.indexOf(tgt.value) === -1) {
quizUrl.push(tgt.value);
e.target.style.backgroundColor = "orange";
// Check if a button is clicked again. If clicked again changes color back and deletes value in the url array.
} else {
quizUrl.splice(quizUrl.indexOf(tgt.value), 1);
e.target.style.backgroundColor = "white";
}
console.log(control.getLink());
console.log(quizUrl)
})
array:
class QuizPart {
constructor(questionText, chosenAnswer, prefix, questionDescription) {
this.questionText = questionText;
this.chosenAnswer = chosenAnswer;
this.prefix = prefix;
this.questionDescription = questionDescription;
}
}
class ChosenAnswer {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
let Quiz = [
new QuizPart('Whats your size?', [
new ChosenAnswer('6595', '41'),
new ChosenAnswer('6598', '42'),
new ChosenAnswer('6601', '43'),
new ChosenAnswer('', ''),
], 'bd_shoe_size_ids=',
'The size of your shoes is very important. If you have the wrong size, they wont fit.'),
new QuizPart('What color would you like?', [
new ChosenAnswer('6053', 'Red'),
new ChosenAnswer('6044', 'Blue'),
new ChosenAnswer('6056', 'Yellow'),
new ChosenAnswer('6048', 'Green'),
new ChosenAnswer('', ''),
], 'color_ids=',
'Color isn t that important, It looks good tho.'),
new QuizPart('What brand would you like?', [
new ChosenAnswer('5805', 'Adidas'),
new ChosenAnswer('5866', 'Nike'),
new ChosenAnswer('5875', 'Puma'),
new ChosenAnswer('', ''),
], 'manufacturer_ids=',
'Brand is less important. Its just your own preference'),
]
I tried giving the array's in link creator and my eventlistener a default value and replacing it when I get and actual value from one of my buttons, but it just doesn't work. Can anybody help me?
I understand, that it might be a bit far from what you expect for an answer - but why don't you have a look at a reactive tool, like Vue? It has all the tools that you might need for such a task, and maybe more:
the whole quiz can be abstracted to a simple array of objects (the questions)
next, prev, set default answer becomes a breeze
easy to extend (with questions)
simple to update (template, features, etc.)
Vue.component('QuizQuestion', {
props: ['data', 'selected'],
computed: {
valSelected: {
get() {
return this.selected
},
set(val) {
this.$emit('update:selected', val)
}
},
},
template: `
<div>
{{ data.text }}<br />
{{ data.description }}<br />
<div class="quiz-options">
<label
v-for="val in data.options"
:key="val[0]"
>
<input
type="radio"
:name="data.text"
:value="val"
v-model="valSelected"
/>
{{ val[1] }}
</label>
</div>
</div>
`
})
new Vue({
el: "#app",
computed: {
currentQuestion() {
return this.questions[this.current]
},
hasPrev() {
return !!this.current
},
hasNext() {
return this.current < this.questions.length - 1
},
},
data() {
return {
current: 0,
questions: [{
text: 'Whats your size?',
description: 'The size of your shoes is very important. If you have the wrong size, they wont fit.',
options: [
['6595', '41'],
['6598', '42'],
['6601', '43'],
['', ''],
],
selected: null,
}, {
text: 'What color would you like?',
description: 'Color isn\'t that important, It looks good tho.',
options: [
['6053', 'Red'],
['6044', 'Blue'],
['6056', 'Yellow'],
['6048', 'Green'],
['', ''],
],
selected: null,
}, {
text: 'What brand would you like?',
description: 'Brand is less important. Its just your own preference',
options: [
['5805', 'Adidas'],
['5866', 'Nike'],
['5875', 'Puma'],
['', ''],
],
selected: null,
}, ],
}
},
methods: {
selectDefault() {
this.questions[this.current] = {
...this.questions[this.current],
selected: this.questions[this.current].options.slice(-1)[0],
}
},
getPrev() {
if (this.hasPrev) {
if (!this.currentQuestion.selected) {
this.selectDefault()
}
this.current -= 1
}
},
getNext() {
if (this.hasNext) {
if (!this.currentQuestion.selected) {
this.selectDefault()
}
this.current += 1
}
},
},
template: `
<div>
<quiz-question
:data="currentQuestion"
:selected.sync="currentQuestion.selected"
/><br />
<button v-if="hasPrev" #click="getPrev">PREV</button>
<button v-if="hasNext" #click="getNext">NEXT</button>
<button v-if="!hasNext">RESULT</button>
</div>
`
})
.quiz-options {
display: flex;
flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
EDIT
But, if frameworks/libraries are not to be used, here's a more OOP approach:
class Quiz {
constructor(questions) {
this._current = 0
this._questions = questions
}
get current() {
return this._current
}
set current(val) {
this._current = val
}
get hasNext() {
return this.current < this.questions.length - 1
}
get hasPrev() {
return !!this.current
}
get questions() {
return this._questions
}
get next() {
this.current = this.hasNext ? this.current + 1 : this.current
return this.currentQuestion
}
get prev() {
this.current = this.hasPrev ? this.current - 1 : this.current
return this.currentQuestion
}
get currentQuestion() {
return this.questions[this.current]
}
}
class Question {
constructor({
text,
description,
options,
prefix,
}) {
this.text = text
this.desc = description
this.prefix = prefix
this._options = options.map(([key, val]) => ({
id: key,
value: [key, val],
selected: false,
}))
}
get options() {
return this._options
}
set options(newOptions) {
this._options = newOptions
}
get selected() {
return this.options.find(({
selected
}) => !!selected)
}
set selected(selectedVal) {
this.options = [...this.options.map(({
value: [key, val],
selected,
...rest
}) => {
return {
...rest,
value: [key, val],
selected: key === selectedVal
}
})]
}
get lastOption() {
return this.options.slice(-1)[0]
}
setDefault() {
if (!this.selected) {
this.selected = this.lastOption.id
}
}
}
const urlParser = (quiz) => {
return quiz.questions.map(({
prefix,
selected = {
value: ['']
}
}) => {
const s = selected.value[0] ? selected.value[0] : ''
return `${prefix}${s}`
}).join('&')
}
const qArr = [{
text: 'text1',
description: 'desc1',
options: [
['1_1', '11'],
['1_2', '12'],
['1_3', '13'],
],
prefix: 'prefix_1_',
},
{
text: 'text2',
description: 'desc2',
options: [
['2_1', '21'],
['2_2', '22'],
['2_3', '23'],
],
prefix: 'prefix_2_',
},
{
text: 'text3',
description: 'desc3',
options: [
['3_1', '31'],
['3_2', '32'],
['3_3', '33'],
],
prefix: 'prefix_3_',
},
]
const getOptionsHtml = ({
text,
options
}) => {
let html = ''
options.forEach(({
id,
value,
selected
}, i) => {
html += `
<label>
<input
class="question-input"
type="radio"
name="${text}"
value="${value[0]}"
${selected ? 'checked' : ''}
/>
${value[1]}
</label>
`
})
return html
}
const getSingleQuestionHtml = (q) => {
const optionsHtml = getOptionsHtml({
text: q.text,
options: q.options
})
return `
${q.text}<br />
${q.desc}<br />
${optionsHtml}
`
}
const registerEventHandlers = ({
container,
question
}) => {
const radioBtns = document.querySelectorAll('.question-input')
radioBtns.forEach((input, i) => {
input.addEventListener('change', function(e) {
question.selected = e.target.value
})
})
}
const updateHtml = ({
container,
question
}) => {
container.innerHTML = getSingleQuestionHtml(question)
registerEventHandlers({
container,
question
})
};
const updateContainer = (container) => (question) => updateHtml({
container,
question
});
const setElDisplay = ({
el,
display
}) => {
if (display) {
el.classList.add("d-inline-block")
el.classList.remove("d-none")
} else {
el.classList.remove("d-inline-block")
el.classList.add("d-none")
}
}
const updateBtnVisibility = ({
btnNext,
btnPrev,
btnResult,
quiz
}) => () => {
setElDisplay({
el: btnNext,
display: quiz.hasNext
})
setElDisplay({
el: btnResult,
display: !quiz.hasNext
})
setElDisplay({
el: btnPrev,
display: quiz.hasPrev
})
}
(function() {
const quiz = new Quiz(qArr.map(q => new Question(q)))
const container = document.getElementById('quiz-container')
updateQuizContainer = updateContainer(container)
updateQuizContainer(quiz.currentQuestion)
const btnPrev = document.getElementById('btn-prev')
const btnNext = document.getElementById('btn-next')
const btnResult = document.getElementById('btn-result')
const updateBtns = updateBtnVisibility({
btnPrev,
btnNext,
btnResult,
quiz
})
updateBtns()
btnPrev.addEventListener('click', function() {
if (quiz.hasPrev) {
quiz.currentQuestion.setDefault()
}
updateQuizContainer(quiz.prev)
updateBtns()
})
btnNext.addEventListener('click', () => {
if (quiz.hasNext) {
quiz.currentQuestion.setDefault()
}
updateQuizContainer(quiz.next)
updateBtns()
})
btnResult.addEventListener('click', function() {
quiz.currentQuestion.setDefault()
console.log(urlParser(quiz))
})
})();
.d-inline-block {
display: inline-block;
}
.d-none {
display: none;
}
<div id="quiz-container"></div>
<div id="quiz-controls">
<button id="btn-prev" class="d-inline-block">
PREV
</button>
<button id="btn-next" class="d-inline-block">
NEXT
</button>
<button id="btn-result" class="d-none">
RESULT
</button>
</div>
<div id="result"></div>
I am developing a chatbot using peekabot (link provided below for documentation and official example), and want to be able to open a URL in a new tab (as you would have the option to do using plain html) when a user clicks on an option. Linked with this is the fact that the URL button that is generated is styled wrong (shows up as blank without the label text on mouse-hover-over).
I have included the whole script below for context, but the bit I am referring to is:
6: {
text: 'You should check it out on test preview',
options: [{
text: "PREVIEW THIS LINK",
url: "www.google.com"
}]
},
The above is option 6 and on clicking it the user should go to the URL (e.g. google.com) but open in a new tab and also not be blank (the button link is blank on hover over for some reason)
I have tried: url: "www.google.com" target="_blank (see below) but this breaks the whole javascript code.
6: {
text: 'You should check it out on test preview',
options: [{
text: "PREVIEW THIS LINK",
url: "www.google.com" target="_blank
}]
},
I have also tried:
url: "www.google.com target="_blank"
and
url: "www.google.com target=_blank"
neither works.
For an answer:
Solution for opening the URL in a new tab
Correction so that the button link (for the URL) is not BLANK on hover-over. (when you move the mouse away from the button link, the text appears)
This is the official site - https://peekobot.github.io/peekobot/ but irritatingly even in their example - the url to GitHub is opened in the same tab.
The whole script below for context:
</script>
<script type="text/javascript" src="<?php echo base_url(''); ?>js/bot.js>v=1"></script>
<script>
const chat = {
1: {
text: 'Some Text here',
options: [{
text: 'More Text here',
next: 101
},
{
text: '??',
next: 201
}
,
{
text: '?????',
next: 301
}
]
},
101: {
text: 'Some information here,
options: [{
text: 'That is great, thanks!',
next: 102
},
{
text: 'I would like some more info please.',
next: 103
}]
},
102: {
text: 'Thanks and Goodbye',
url: siteurl + "index.php/student/test",
options: [{
text: 'Bye and thank you.',
next: 3
},
{
text: 'I would like some more info please.',
next: 104
}]
},
103: {
text: 'Info here',
options: [{
text: 'That is great, thanks!',
next: 103
},
{
text: 'I would like some more info please.',
next: 104
}]
},
5: {
text: 'Aah, you\'re missing out!',
next: 6
},
6: {
text: 'You should check it out on test preview',
options: [{
text: "Go to PRIVIEW",
url: "www.google.com"
}]
},
};
const bot = function () {
const peekobot = document.getElementById('peekobot');
const container = document.getElementById('peekobot-container');
const inner = document.getElementById('peekobot-inner');
let restartButton = null;
const sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};
const scrollContainer = function () {
inner.scrollTop = inner.scrollHeight;
};
const insertNewChatItem = function (elem) {
//container.insertBefore(elem, peekobot);
peekobot.appendChild(elem);
scrollContainer();
//debugger;
elem.classList.add('activated');
};
const printResponse = async function (step) {
const response = document.createElement('div');
response.classList.add('chat-response');
response.innerHTML = step.text;
insertNewChatItem(response);
await sleep(1500);
if (step.options) {
const choices = document.createElement('div');
choices.classList.add('choices');
step.options.forEach(function (option) {
const button = document.createElement(option.url ? 'a' : 'button');
button.classList.add('choice');
button.innerHTML = option.text;
if (option.url) {
button.href = option.url;
} else {
button.dataset.next = option.next;
}
choices.appendChild(button);
});
insertNewChatItem(choices);
} else if (step.next) {
printResponse(chat[step.next]);
}
};
const printChoice = function (choice) {
const choiceElem = document.createElement('div');
choiceElem.classList.add('chat-ask');
choiceElem.innerHTML = choice.innerHTML;
insertNewChatItem(choiceElem);
};
const disableAllChoices = function () {
const choices = document.querySelectorAll('.choice');
choices.forEach(function (choice) {
choice.disabled = 'disabled';
});
return;
};
const handleChoice = async function (e) {
if (!e.target.classList.contains('choice') || 'A' === e.target.tagName) {
// Target isn't a button, but could be a child of a button.
var button = e.target.closest('#peekobot-container .choice');
if (button !== null) {
button.click();
}
return;
}
e.preventDefault();
const choice = e.target;
disableAllChoices();
printChoice(choice);
scrollContainer();
await sleep(1500);
if (choice.dataset.next) {
printResponse(chat[choice.dataset.next]);
}
// Need to disable buttons here to prevent multiple choices
};
const handleRestart = function () {
startConversation();
}
const startConversation = function () {
printResponse(chat[1]);
}
const init = function () {
container.addEventListener('click', handleChoice);
restartButton = document.createElement('button');
restartButton.innerText = "Restart";
restartButton.classList.add('restart');
restartButton.addEventListener('click', handleRestart);
container.appendChild(restartButton);
startConversation();
};
init();
}
bot();
</script>
UPDATE:
Based on a suggestion below, I've tried:
if (step.options) {
const choices = document.createElement('div');
choices.classList.add('choices');
step.options.forEach(function (option) {
const button = document.createElement(option.url ? 'a' : 'button');
button.classList.add('choice');
button.innerHTML = option.text;
if (option.url) {
button.href = option.url;
if (option.target) {
button.target = option.target;
} else {
button.dataset.next = option.next;
}
choices.appendChild(button);
});
insertNewChatItem(choices);
} else if (step.next) {
printResponse(chat[step.next]);
}
};
This breaks the whole code so the chatbot doesn't run at all.
What I'm thinking is you would have to modify the code or get the author to modify the code for you.
I'm looking at the main js code here: https://github.com/Peekobot/peekobot/blob/master/peekobot.js
This snippet is what I am looking at:
step.options.forEach(function (option) {
const button = document.createElement(option.url ? 'a' : 'button');
button.classList.add('choice');
button.innerHTML = option.text;
if (option.url) {
button.href = option.url;
} else {
button.dataset.next = option.next;
}
choices.appendChild(button);
});
That last part would get changed to something like this, I would think.
if (option.url) {
button.href = option.url;
if (option.target) {
button.target = option.target;
}
} else {
...
I'm creating a map based on this example:
https://labs.mapbox.com/education/impact-tools/finder-with-filters/
In their example, they have two dropdown filters and one checkbox filter. I would like to have three checkbox filters. I created three checkbox filters, and on their own, they seem to work well. The issue is that the filters seem to override each other in the order clicked. In their example, the filters seem to be working together, so I can't figure out why it's not working anymore when I changed the filter type.
Here's the code for my project:
https://codepen.io/flyinginsect2/pen/eYdyqxZ
Here are snippets of the code relevant to filtering:
const config = {
style: "mapbox://styles/mapbox/light-v10",
accessToken: "pk.eyJ1IjoibGF1cmFqZWFudGhvcm5lIiwiYSI6ImNraXl5M29oMDEyMjgzM3BhNTh1MGc1NjkifQ.g4IAFIrXPpl3ricw3f_Onw",
CSV: "https://docs.google.com/spreadsheets/d/106xm254us29hAUEtR7mTo0hwbDJv8dhyQs9rxY601Oc/gviz/tq?tqx=out:csv&sheet=Attributes",
center: [-104.339, 46.869],
zoom: 2,
title: "ENVIROlocity Mapper",
description: "Environmental Networking, Volunteering, Internship, and R.... Opportunities",
sideBarInfo: ["Org_name", "CityState"],
popupInfo: ["Org_name"],
filters: [
{
type: "checkbox",
title: "Sector: ",
columnHeader: "Sector",
listItems: ["Local Government", "Nonprofit"]
},
{
type: "checkbox",
title: "Industry: ",
columnHeader: "Industry_type",
listItems: ["Conservation", "Policy"]
},
{
type: "checkbox",
title: "Internships: ",
columnHeader: "internships_YN",
listItems: ["Yes"]
}
]
};
const selectFilters = [];
const checkboxFilters = [];
function createFilterObject(filterSettings) {
filterSettings.forEach(function (filter) {
if (filter.type === 'checkbox') {
columnHeader = filter.columnHeader;
listItems = filter.listItems;
const keyValues = {};
Object.assign(keyValues, { header: columnHeader, value: listItems });
checkboxFilters.push(keyValues);
}
if (filter.type === 'dropdown') {
columnHeader = filter.columnHeader;
listItems = filter.listItems;
const keyValues = {};
Object.assign(keyValues, { header: columnHeader, value: listItems });
selectFilters.push(keyValues);
}
});
}
function applyFilters() {
const filterForm = document.getElementById('filters');
filterForm.addEventListener('change', function () {
const filterOptionHTML = this.getElementsByClassName('filter-option');
const filterOption = [].slice.call(filterOptionHTML);
const geojSelectFilters = [];
const geojCheckboxFilters = [];
filteredFeatures = [];
filteredGeojson.features = [];
filterOption.forEach(function (filter) {
if (filter.type === 'checkbox' && filter.checked) {
checkboxFilters.forEach(function (objs) {
Object.entries(objs).forEach(function ([key, value]) {
if (value.includes(filter.value)) {
const geojFilter = [objs.header, filter.value];
geojCheckboxFilters.push(geojFilter);
}
});
});
}
if (filter.type === 'select-one' && filter.value) {
selectFilters.forEach(function (objs) {
Object.entries(objs).forEach(function ([key, value]) {
if (value.includes(filter.value)) {
const geojFilter = [objs.header, filter.value];
geojSelectFilters.push(geojFilter);
}
});
});
}
});
if (geojCheckboxFilters.length === 0 && geojSelectFilters.length === 0) {
geojsonData.features.forEach(function (feature) {
filteredGeojson.features.push(feature);
});
} else if (geojCheckboxFilters.length > 0) {
geojCheckboxFilters.forEach(function (filter) {
geojsonData.features.forEach(function (feature) {
if (feature.properties[filter[0]].includes(filter[1])) {
if (
filteredGeojson.features.filter(
(f) => f.properties.id === feature.properties.id
).length === 0
) {
filteredGeojson.features.push(feature);
}
}
});
});
if (geojSelectFilters.length > 0) {
const removeIds = [];
filteredGeojson.features.forEach(function (feature) {
let selected = true;
geojSelectFilters.forEach(function (filter) {
if (
feature.properties[filter[0]].indexOf(filter[1]) < 0 &&
selected === true
) {
selected = false;
removeIds.push(feature.properties.id);
} else if (selected === false) {
removeIds.push(feature.properties.id);
}
});
});
removeIds.forEach(function (id) {
const idx = filteredGeojson.features.findIndex(
(f) => f.properties.id === id
);
filteredGeojson.features.splice(idx, 1);
});
}
} else {
geojsonData.features.forEach(function (feature) {
let selected = true;
geojSelectFilters.forEach(function (filter) {
if (
!feature.properties[filter[0]].includes(filter[1]) &&
selected === true
) {
selected = false;
}
});
if (
selected === true &&
filteredGeojson.features.filter(
(f) => f.properties.id === feature.properties.id
).length === 0
) {
filteredGeojson.features.push(feature);
}
});
}
map.getSource('locationData').setData(filteredGeojson);
buildLocationList(filteredGeojson);
});
}
function filters(filterSettings) {
filterSettings.forEach(function (filter) {
if (filter.type === 'checkbox') {
buildCheckbox(filter.title, filter.listItems);
} else if (filter.type === 'dropdown') {
buildDropDownList(filter.title, filter.listItems);
}
});
}
function removeFilters() {
let input = document.getElementsByTagName('input');
let select = document.getElementsByTagName('select');
let selectOption = [].slice.call(select);
let checkboxOption = [].slice.call(input);
filteredGeojson.features = [];
checkboxOption.forEach(function (checkbox) {
if (checkbox.type == 'checkbox' && checkbox.checked == true) {
checkbox.checked = false;
}
});
selectOption.forEach(function (option) {
option.selectedIndex = 0;
});
map.getSource('locationData').setData(geojsonData);
buildLocationList(geojsonData);
}
function removeFiltersButton() {
const removeFilter = document.getElementById('removeFilters');
removeFilter.addEventListener('click', function () {
removeFilters();
});
}
createFilterObject(config.filters);
applyFilters();
filters(config.filters);
removeFiltersButton();
I read this Mapbox documentation on combining filters, but I can't figure out how to work it in.
https://docs.mapbox.com/mapbox-gl-js/style-spec/other/#other-filter
I know there are many other Stack Exchange posts out there that address filtering on multiple criteria, but I can't find one that seems to address this specific issue.
The issue is in the space in value for "Local Government"
If you look at the generated HTML you will see a space in the id, which is not valid HTML
<input class="px12 filter-option" type="checkbox" id="Local Government" value="Local Government">
Just remove the whitespaces when building the HTML id attribute
input.setAttribute('id', listItems[i].replace(/\s/g,''));
I need to get my checkboxes in todo list read from object in array if task is complete or not. And stay checked when they're complete and unchecked or not.
const todos = [
{
id: 1,
title: 'Nakupit',
description: 'Mlieko, syr, vajcia',
completed: false,
},
{
id: 2,
title: 'Umyt auto',
description: '+ povysavat',
completed: true,
},
]
This is the array and i tried on checkbox something like this. And variations, unable to get it work and changing array or value from array making checkbox ,checked, if complete
toDoCheckbox.addEventListener('click', () => {
if (toDoCheckbox.checked = true) {
return todos.completed === true
} else {
return todos.completed === false
}
});
Can anyone help with it?
You can modify the todos state by looking it up by its id and flipping its completed status.
I added the button to request re-rendering. This will re-build the checkboxes using the current state.
const todos = [{
id: 1,
title: 'Nakupit',
description: 'Mlieko, syr, vajcia',
completed: false,
}, {
id: 2,
title: 'Umyt auto',
description: '+ povysavat',
completed: true,
}]
const main = () => {
const btn = document.querySelector('.btn-render')
btn.addEventListener('click', reRender)
renderTodos()
}
const reRender = (e) => {
renderTodos()
}
const onCheck = (e) => {
const id = parseInt(e.currentTarget.dataset.id, 10)
const found = todos.find(todo => todo.id === id)
if (found) {
found.completed = !found.completed // Flip status
}
}
const renderTodos = () => {
const container = document.querySelector('.container')
container.innerHTML = '' // Clear
todos.forEach(todo => {
let wrapper = document.createElement('div')
let label = document.createElement('label')
let checkbox = document.createElement('input')
wrapper.classList.add('checkbox-wrapper')
label.textContent = todo.title
checkbox.type = 'checkbox'
checkbox.checked = todo.completed
checkbox.dataset.id = todo.id
checkbox.addEventListener('change', onCheck)
wrapper.appendChild(label)
wrapper.appendChild(checkbox)
container.appendChild(wrapper)
})
}
main()
.checkbox-wrapper label {
display: inline-block;
width: 6em;
}
<div class="container"></div>
<br />
<button class="btn-render">Re-render</button>
I'm new to Javascript and I'm running into an issue when building a todo list. I'm trying to add a checkbox that will push the #id to handlers.toggleCompleted and in turn mark the item as completed.
I'm able to correctly run the if statement
if (elementChecked.childNodes[3].checked) {
console.log(elementClicked.parentNode.id);
However I get the Uncaught RefferenceError here
if (elementChecked.childNodes[3].checked) {
handlers.toggleCompleted(elementChecked.parentNode.id);
Here is the full code, sorry if this isn't a good question I'm still learning the language.
let todoList = {
todos: [],
addTodo: function(todoText) {
this.todos.push({
todoText: todoText,
completed: false
});
},
changeTodo: function(position, todoText) {
this.todos[position].todoText = todoText;
},
deleteTodo: function(position) {
this.todos.splice(position, 1);
},
toggleCompleted: function(position) {
let todo = this.todos[position];
todo.completed = elementChecked.childNodes[3].checked;
},
toggleAll: function() {
let totalTodos = this.todos.length;
let completedTodos = 0;
// Get number of completed todos.
this.todos.forEach(function(todo) {
if (todo.completed === true) {
completedTodos++;
}
});
this.todos.forEach(function(todo) {
//case 1: if everything is true make everything flase
if (completedTodos === totalTodos) {
todo.completed = false;
} else {
//case 2: if everything is false make everything true
todo.completed = true;
}
});
}
};
let handlers = {
addTodo: function() {
let addTodoTextInput = document.getElementById('addTodoTextInput');
todoList.addTodo(addTodoTextInput.value);
addTodoTextInput.value = '';
view.displayTodos();
},
changeTodo: function(position, todoText){
todoList.changeTodo(position, todoText);
view.displayTodos();
},
deleteTodo: function(position) {
todoList.deleteTodo(position);
view.displayTodos();
},
toggleCompleted: function(position) {
todoList.toggleCompleted(position);
view.displayTodos();
},
toggleAll: function() {
todoList.toggleAll();
view.displayTodos();
}
};
let view = {
displayTodos: function() {
let todosUl = document.querySelector('ul');
todosUl.innerHTML = '';
todoList.todos.forEach(function(todo, position) {
let todoLi = document.createElement('li');
let todoTextWithCompletion = '';
if (todo.completed === true) {
todoTextWithCompletion = '(x) ' + todo.todoText;
} else {
todoTextWithCompletion = '( ) ' + todo.todoText;
}
todoLi.id = position;
todoLi.textContent = todoTextWithCompletion;
todoLi.appendChild(this.createDeleteButton());
todoLi.appendChild(this.createChangeButton());
todoLi.appendChild(this.createCompleteButton());
todosUl.appendChild(todoLi);
}, this);
},
createDeleteButton: function() {
let deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.className = 'deleteButton';
return deleteButton;
},
createChangeButton: function() {
let changeButton = document.createElement('button');
changeButton.textContent = 'Change';
changeButton.className = 'changeButton';
return changeButton;
},
createCompleteButton: function() {
let completeButton = document.createElement('input');
completeButton.setAttribute("type", "checkbox");
completeButton.className = 'todoComplete';
return completeButton;
},
setUpEventListeners: function() {
let todosUl = document.querySelector('ul');
todosUl.addEventListener('click', function(event) {
let elementClicked = event.target;
let elementChecked = document.getElementById(parseInt(elementClicked.parentNode.id));
if (elementClicked.className === 'deleteButton') {
handlers.deleteTodo(parseInt(elementClicked.parentNode.id));
}
if (elementClicked.className === 'changeButton') {
let selectedTodoText = parseInt(elementClicked.parentNode.id);
let changedTextValue = prompt("Please enter new text:", selectedTodoText);
handlers.changeTodo(selectedTodoText, changedTextValue);
}
if (elementChecked.childNodes[3].checked) {
handlers.toggleCompleted(elementClicked.parentNode.id);
console.log(elementClicked.parentNode.id);
} else {
elementChecked.style.background = 'transparent';
}
});
}
};
view.setUpEventListeners();
Figured it out (kind of) it was because it wasn't defined in the todoList.toggleCompleted scope.