Utilizing vanilla JavaScript to sort selected checkboxes into a JSON object

I've been trying to implement a difficulty filter based on checked checkboxes, but despite my ongoing search for solutions, I haven't been able to find any promising results or clear directions.

Exploration

I came across a code snippet that seems to be effective, but it's designed for jQuery and using this doesn't seem to work in pure JS. I also found an example using

for ( i = 0; i < difficultyFi.length; i++ )
, but I'm uncertain about its correctness.

My experience with JavaScript is mostly limited to jQuery, making it challenging to achieve a similar outcome using plain JS.

Outcome

The approach involves locating all elements with the class .difficultyFi, extracting their values to create an array named availableDifficulty, identifying which checkboxes are :checked, and then adding their values to another array called activeDifficulty.

Final Thoughts

Once this process is implemented successfully, my plan is to use the activeDifficulty array to filter my main JSON data set. This task will definitely be tackled in the future!

If anyone could provide assistance, it would be greatly appreciated!

// Filter difficulty

var availableDifficulty = [];
var activeDifficulty = [];
var difficultyFi = document.querySelectorAll('.difficultyFi');
console.log( difficultyFi );

difficultyFi.forEach( function() {
    
    var difVal = this.value();
    
    availableDifficulty.push( difVal );
    console.log( difVal );
    
    if ( this.hasAttribute( 'checked' ) ) {
        activeDifficulty.push( difVal );
        console.log( difVal );
    }
    
});

Answer №1

To streamline the process, utilize a few concise helper functions. The spread operator [...checkboxes] is employed to transform the array-like NodeList obtained from querySelectorAll into an actual array, allowing you to apply map on it. The use of map is to generate an array of objects containing checkbox elements and their corresponding values. The function getActiveVals employs filter to select only checked elements. Another instance of map transforms the resulting object into its value string, such as "d_e".

const checkboxes = document.querySelectorAll('.difficultyFi');
const difficultyVals = [...checkboxes].map(e => ({ el: e, val: e.value }));
const getActiveVals = () => difficultyVals.filter(({el}) => el.checked).map(({val}) => val);

checkboxes.forEach(e => e.addEventListener('change', () => console.log(getActiveVals())));
<div>
    <input type="checkbox" class="difficultyFi" value="d_e" checked> easy<br>
    <input type="checkbox" class="difficultyFi" value="d_m"> moderate<br>
    <input type="checkbox" class="difficultyFi" value="d_h"> hard<br>
  </div>

Answer №2

I had overlooked the option of defining specific attributes as parameters within the function. By simply indicating element, value, I was able to get the desired outcome instead of relying on this.value().

var availableDifficulty = [];
var activeDifficulty = [];
var difficultyFi = document.querySelectorAll('.difficultyFi');

difficultyFi.forEach( function(element, value) {

    var difVal = element.value;

    availableDifficulty.push( difVal );

    if ( element.hasAttribute( 'checked' ) ) {
        activeDifficulty.push( difVal );
    }

});

console.log( activeDifficulty );
<div class="form-check form-switch">
  <input class="form-check-input difficultyFi" type="checkbox" role="switch" value="d_e" checked>
  <label class="form-check-label" for="d_e">Easy</label>
</div>

<div class="form-check form-switch">
  <input class="form-check-input difficultyFi" type="checkbox" role="switch" value="d_m" checked>
  <label class="form-check-label" for="d_m">Moderate</label>
</div>

<div class="form-check form-switch">
  <input class="form-check-input difficultyFi" type="checkbox" role="switch" value="d_h" checked>
  <label class="form-check-label" for="d_h">Hard</label>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Restricting the Zoom Functionality in a Web-Based Project on a Touch-Enabled Display

I am currently working on a project that is web-based and runs on localhost. I need to prevent users from zooming in on the user interface. Is there a way to accomplish this using JavaScript? And can I achieve this restriction specifically on Google Chrome ...

How to utilize JSON for decoding information in PHP

I am in need of decoding this Json using PHP, but I am not sure how to do it. I have looked at the function on php.net/json, but it does not provide instructions on how to decode this specific type of data. {"c":[{"v":"0","e":"","n":"45","cc":"PSDB - PT ...

Utilize Ajax and PHP to transfer User ID to the Database

One issue I'm facing is that I have a page where my users' posts are displayed, and each post has a connect button in the form of form input. The poster's id is associated with each post. I want it so that when a user clicks on the connect b ...

Swapping characters from the beginning and end of a specific string

Consider the following scenario: b*any string here* If this pattern is present, I would like to substitute b* at the beginning with <b>, and the * at the end with </b> (Ignore the backslash for SO site escaping). It's possible that ther ...

Leveraging jQuery event listeners within a Javascript class initialization

Recently delving into OOP in JavaScript, I've been revamping some of my old code to make it more reusable. Instead of leaving them as inline scripts, I decided to encapsulate them within JavaScript classes. Here is an example of one of my classes: ...

Is it possible to update the variable value in one controller from another controller after an http.get request has been made

I have encountered an issue with updating a variable from one controller to another using a service. Despite my efforts, the variable is not being updated. The goal is to have the variable $scope.names in controller 'select' update in controller ...

When I integrate the Google map on my website, it appears to be fully zoomed out by default. However, if you access the map directly through the link provided, it

After creating a custom public map on google.maps, I noticed that the embedded version on my site is zoomed out too far and not centered on my location like the original. You can view it here. Here's the code I'm using to embed the map: <ifr ...

Creating a dynamic dropdown menu that displays options based on the selection made in a previous drop

Attempting to replicate this exact functionality on my own site has proven difficult. Despite success on jsfiddle, none of the browsers I've tested seem to cooperate. Any suggestions? Even when isolated as the sole element on a page, it simply refuses ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

What is the best way to generate script code dynamically on an HTML page depending on the environment?

I am facing a challenge with my asp.net application. I need to insert a dynamic script into the html section, and this script's value must change depending on the environment (TEST, QA, etc.). To illustrate, here is the script where DisplayValue is th ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

Ways to utilize the Math.max and Math.min functions within an Array

Attempting to use this approach on an array to retrieve both the minimum and maximum values proved unsuccessful. var array = [3, 6, 1, 5, 0, -2, 3]; var min = Math.min( array ); var max = Math.max( array ); document.write(max); ...

SBJsonParser tried to use an invalid method with instance 0x6695330, resulting in an NSInvalidArgumentException error

Encountered an issue while developing a login view for my iPhone app. The error message reads: 'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]: unrecognized selector sent to instance 0x6695330' The l ...

Can you explain the distinction between these two lines of code in JavaScript and jQuery?

As a newcomer to javascript and jquery, I am encountering an issue with getting jquery to work properly. I'm puzzled by the difference between these two statements: console.log ($("#FirstName").value); console.log(document.getElementById('FirstN ...

What is the best way to modify the style class and content of text for parent elements in this d3.js tree structure?

This is a follow-up to this question. (Special thanks to Cyril for the assistance!) There is a slight complication with my issue and I require further assistance. When a user clicks on any text element of a node, I aim for the following actions to take pl ...

How to read post data in JSON format using body-parser in a Node.js Express

I have included the dependencies "body-parser": "1.15.0" and "express": "4.13.4" I am attempting to extract the json data from the body section of an incoming http post request. This is the code I am using: var express = require('express'); var ...

Developing an HTML form that sends data to a server using JSON code

Currently, my goal is to develop a code that includes 4 user input fields and sends the data to a server using JSON. While I am new to working with JSON, I do have experience in HTML. However, I am facing some challenges figuring out where to begin. ...

Could Angular2's Http Get method exclusively handle Json data?

mma-api.service.ts getAthletes() { return this.http.get('http://mma-data-api.mma.com/api/v3/athletes') .map(res => res.json()); } athlete.component.ts data: string; constructor(private mmaApiService: MmaApiService) ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...