push checked box values into an array using javascript - javascript

I have a bunch of check boxes and the value of each one is a different price. I created an object that holds the function to push the values into an array if the box is checked. When I console log the empty array it displays as empty so i know that works. I just cant get it to console log with the pushed value in it.
<input type="checkbox" id="bac" value ="1">bacon - $1
var allIngredients = {
ingredientArray: [],
baconBox: function() {
var bacon = document.getElementById('bac');
if (bacon.checked === true) {
this.ingredientArray.push(bacon.value);
}
},
edit:
console.log(allIngredients.ingredientArray);
that returns an empty array like this "[]". I cannot get it to return an array with the value of bacon in it like this "[1]" when i check the box. The value of bacon is 1.

As others have pointed out in the comments, you should call the function allIngredients.baconBox().
One option is to add an event listener, like so:
document.getElementById('bac').addEventListener('change', function() {
allIngredients.baconBox();
});
Although a downside of this approach is that unchecking the box wouldn't remove the bacon.value from your allIngredients array.

Related

Vue trying to filter an array but I get no results

I have a Vue 3 application
I have an object of posts. Each post has a different category. At the top of the page I have check boxes that I can check to filter the array and only show the categories I added to another array called visibleList. If I click the check box for cars then 'cars' is added to visibleList.
I need to show only posts with the category of cars if I check the cars checkbox. Now if I check the box I see no posts
I created an extra object that I can use to filter the objects. That object is populated when I load the app.
When I check a box the posts disappear. In the console I can see the number of posts with the correct category showing true and the others showing false.
Here is my function for sorting the posts:
function filterPosts() {
filtered.value = posts.value;
if (visibleList.value.length != 0) {
filtered.value = filtered.value.filter((e) => {
visibleList.value.includes(e.category);
console.log(visibleList.value.includes(e.category));
});
} else {
filtered.value = posts.value;
}
}
What am I doing wrong that I cannot see the posts from the selected category?
Looks like you are not returning a value from the filter function. The filter function expects a boolean value to determine whether an element should be included in the filtered array or not.
filtered.value = filtered.value.filter((e) => {
return visibleList.value.includes(e.category);
});
Just an Alternative!!
Since you are using the arrow function, you can use this approach to filter down the value.
filtered.value = filtered.value.filter((e) => visibleList.value.includes(e.category));

Comparing the data attribute value of 2 arrays and checking the innerHTML of the selected checkbox

I am using Vanilla JS and PHP. I have a series of checkboxes for blog posts. Each post has its own associated checkbox and on each checkbox there is a value which is the equivalent of the postID from the mysql db. I have a foreach checking the checkboxes to see which one is clicked and then it pushes that value onto an empty array.
I also have a 2nd array that is filled with the posts id using a separate data attribute as the elements are not on the same DOM level. The 2nd array values contain a status within a <span> that either say 'Published' or 'Draft'. The span has its own data- attribute identifying the post id. I want to compare ids from both arrays and check the innerHTML of the span belonging to the 2nd array. Right now I have a check in place but it only checks the first value int the 2nd array.
Checkbox foreach
//Store post id from checkbox
let checkBox = document.querySelectorAll('.postCheckBox');
let postIDs = [];
let blogIDs = [];
checkBox.forEach(function (element) {
if (element.checked) {
//Store POST ids
postIDs.push(element.value);
//Store BLOG ids
blogIDs.push(element.dataset.blog);
}
});
and in the dom it looks like (the value is the postID)
<input type="checkbox" class="postCheckBox" value="5" data-blog="1">
My 2nd array with values
let customPostIds = [];
Array.prototype.slice.call(postStatus).forEach(post => {
customPostIds.push(post);
})
console.log(customPostIds)
which when consoled returns
And in each of those elements I do see dataset and the innerHTML just not sure how to use it to compare it to the first array AND extract the innerHTML to do a check.
If you need more info to give feedback let me know so I can add whatever info is needed.
The end result I am hoping to achieve is to have a valid if statement check. Pseudo code:
if((postID.id === customPostIds.id) && customPostIds.innerHTML === 'Draft') {return true;}
The tricky part is that customPostIds needs 2 values extracted from it... 1) The data-post-id and the innerHTML from each item in the array. However, the dataset.postId and the innerHTML from the customPostIds array which I want to extract, do not live on the same HTML element in the DOM.

How to use a index value of a dynamic array (which get filled by a click event) for filtering a new array

I'm working on a filter, which filters a array of nested arrays down to the value of one last index.
This happens in 5 steps. At each step you choose which index value (string) get used to filter the array further.
Example: You have 5 categories, each have 6 themes. Each of these 6 themes has 6 focusses(sub themes). Each focus has 6 questions. Each question has 1 answer. First you pick a categorie. This narrows the arrays down to all arrays with that categorie. Then a theme, which narrows the array down to only the arrays with that theme... etc...
So far I managed to filter down to the right question.
You can find the code here: https://github.com/okestens/vertical-filter.git
To get this work, I hardcoded the string "Deskundigheid" as a condition for the equality operator (===) that get used for the filter.
Example:
// FILTER QUESTIONS // I tried to use state.focus[0] but it does not work
let unique_questionsA = [. // now this is hardcoded
...new Set(formsA.filter((i) => i[2] === "Deskundigheid").map((i) => i[3])),
]; --------------
// FUNCTION
function displayQuestionsA() {
state.questions = [];
unique_questionsA.forEach(function (question, index) {
document.getElementById("question" + index).innerHTML = question;
state.questions.push(question);
});
------
// the state object
let state = {
category: [],
themes: [],
focus: [],
question: [],
answer: [],
};
But. What I want this filter to use is not a hardcoded string (deskundigheid) but the exact string that is visible in the div (coming from a click event which creates this filtered array and get stored in the state object). See image.
I thought: I need to track these arrays (with an object called 'state', capturing these dynamic arrays). If I then want to filter the right questions, by using the value (string) of the chosen focus (For example 'Deskundigheid', which is visible to the user), I just refer to the corresponding index value (state.focus[0]) of that chosen focus string, coming from the dynamic state object.
But, if I use the index state.focus[0] for the filter which creates the questions array, I get an empty array :(
My thought: Although the empty focus array (inside the state object), which get filled by a click event, eventually is filled with the right strings, the filter for the new array (unique_questionsA), which uses 'state.focus[0]' does not read the filled array as ‘filled’ but as empty.
I have not idea why :(
I hope I'm clear. If so, and you maybe have a clue, I would love to have a chat! Thanks O
The question can be summed up to
how do I get the text of the element when clicked, in an onclick event
listener callback function.
Your focusScript.js can be modified to
function displayQuestionsA(e) {
state.questions = [];
let unique_questionsA = [...new Set(formsA.filter((i) => i[2] === e.target.innerText).map((i) => i[3]))];
}
document.querySelector(".focus__A").addEventListener("click", displayQuestionsA);
Notice the e.target.innerText which contains the text inside the element that triggered the event(which you clicked).
if I got you correctly - both map and filter functions can give your callback second parameter - the index.
arr.map((n,i)=>{console.log(`[${i}]:${n}`)})

How to select a key/value pair with two further keys/values nested inside?

I am using the below code to iterate through a JSON object which has a dynamic key at the top level.
for (var key in data.query.results.json) {
if(firstSkipped == false) {
firstSkipped = true; // sets skipping variable to true so condition is met on next iteration
} else {
for (var key2 in data.query.results.json[key]) {
if(key2 == "http:__purl.org_rss_1.0_title")
titles.push(data.query.results.json[key][key2].value); // pushes titles to array
It works fine however, I need to add another field which is complicating things. The fields below all just have a single value inside them, however, the new field I need to add has a further two keys, each with a value. I need to select just one of these and display the value. I've tried doing the following but I just get 'undefined'.
for (var key3 in data.query.results.json[key]) {
if(key3 == "0")
isbns.push(data.query.results.json[key][key2][key3].value); // pushes urls to array
}
I'm just trying to select the 3rd Key down, then search through each field until it finds the key called '0', then push its value to an array.
Any ideas where I'm going wrong? I can try and post a sample of the JSON if it doesn't make sense without seeing it.
Here is what the data looks like (it is the ISBN field I'm trying to get to):

How can I post a bunch of checkbox names to an array?

I'm looking to get a bunch of checkboxes (all with the same class) and get all the attribute names and push all the checked boxes into an array (also remove them from the array if they get unchecked).
Eventually, I want to pass an array of what was checked via ajax, and the ajax refreshes every time a box is checked/unchecked.
Any ideas on how I'd do this?
Use $.map to get all the names of checkboxes in an array.
var names = $('.theClassName').map(function() {
return this.name;
});
For second part of your question.
To get only checked checkboxes use $('.theClassName:checked'). You don't have to maintain an array for this.
Try the following
var names = [];
$('.theClassName').each(function() {
var name = $(this).attr('name');
names.push(name);
});
var names = $('input.class_name:checked').map(function {
return $(this).attr('name');
})
will fill an array with the names of the checked checkboxes.

Categories

Resources