Creating a function to determine if at least one checkbox has been selected

<div class="form-group">
<div class="row" style="margin-top: 10px;">
<div class="weekDays-selector checkbox-inline" 
     ng-repeat="day in vm.days" 
     ng-if="vm.pen.feeding_frequency.name == 'Custom'">
<input type="checkbox" ng-click="function()"
       id="custom_frequency{{$index}}" 
       name="custom_frequency" 
       class="weekday" / >
<label for="custom_frequency{{$index}}">{{day.name}}</label>
</div>

This section of my HTML code is responsible for generating checkboxes based on a predefined object

The structure of the object is as follows:

vm.days = [{
            name: i18nFilter('_custom_day_monday_'),
            value: 1
        }, {
            name: i18nFilter('_custom_day_tuesday_'),
            value: 2
        }, {
            name: i18nFilter('_custom_day_wednesday_'),
            value: 3
        }, {
            name: i18nFilter('_custom_day_thursday_'),
            value: 4
        }, {
            name: i18nFilter('_custom_day_friday_'),
            value: 5
        }, {
            name: i18nFilter('_custom_day_saturday_'),
            value: 7
        }, {
            name: i18nFilter('_custom_day_sunday_'),
            value: 7
        }]

Now, I am looking for a way to determine if any of these dynamically generated checkboxes are checked. Any suggestions on how I can achieve that?

Answer №1

To customize the checkbox, you can make the following modifications:

<input type="checkbox" id="custom_frequency{{$index}}" ng-model="vm.selected[$index]" ng-init="vm.selected[$index]=false" name="custom_frequency" on class="weekday" / >

As a result, a scope variable named selected will be created within your vm object. By default, this object will contain 7 false values. When you select a weekday, the corresponding index in the object will be updated to true.

You can then filter this array to determine the number of checked items using the following code in the TypeScript file:

var found = Object.keys($scope.vm.selected).filter(function(key) {
 return $scope.vm.selected[key] === true;
});
console.log(found.length)

Answer №2

Retrieve all the checkboxes using document.querySelector and then utilize the array some method to verify if any of them are selected.

[...document.querySelectorAll('.days')].some(entry => entry.checked)

Answer №3

To detect checked elements, you can utilize the :checked selector:

const checkedWeekdays = document.querySelectorAll(".weekday:checked").length;     // Returns zero if none are checked

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

all-encompassing ajax call method with jquery

Is there a universal function for calling ajax requests globally? For example, instead of writing the same code multiple times: $.ajax({ url: some_url_address, type: 'post', data: $('#form').serialize(), dataType: &apos ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

Exploring parameterized routing in Node.js and Express

I am currently facing an issue with my node.js API where I have two separate routes set up. One route is for retrieving user data by ID, while the other is a general user endpoint. Here are the routes: app.get('/api/v1/user/:userid', function (r ...

Creating a custom function in JavaScript to interact with the `windows.external` object specifically for use

In my current project, I am facing an issue with JavaScript file compatibility across different browsers. Specifically, I have a JavaScript file that calls an external function (from a separate file) using windows.external, like this: windows.external.se ...

jsTree eliminates the hashtag from the URL

Utilizing a JSON generated jsTree to efficiently navigate through a directory structure has been my recent task. I have successfully implemented the select_node event to capture the path of the selected node as a string and then update the location.hash ...

Format the date using moment() for the last week of the current year and return it with the year. Next year's

I encountered an unusual problem when using Moment.js with Angular.js. When I use the .toISOString() method, I get the correct date, but when I use the .format() method, the date is completely wrong. Here is an example to illustrate the issue: Code snip ...

Execute JavaScript/AJAX solely upon the selection of a button

Currently, my script is being executed immediately after the page loads and then again after a button click. Is there any way to modify it so that the script waits until I click the button before running? As far as I understand, this code runs asynchronous ...

Mongoose .lean() Method Causes Equality Test to Fail

In my quest to compare req.user._id with an array of ObjectIds obtained from a MongoDB query, I encountered failures in all my attempts using .includes(), as well as strict and loose equality checks. Below is a simplified version of the logic in my contro ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Solving template strings in a future context

I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this? var blog_entries_dom = 'blog_entries& ...

What is the best way to ensure my arrow text remains properly positioned when using fullpage.js?

Seeking guidance from the web development community. I am currently working on a client's website that utilizes fullpage.js and encountering a persistent issue. On slide1 of the website, I am struggling to display the correct text next to the arrows. ...

Dividers afloat - expanding current script with multiple additions

I am currently utilizing this website as a hub for showcasing my various web projects. The jsfiddle code provided in response to this particular inquiry is exactly what I need, however, I am unsure of how to have multiple divs moving simultaneously acros ...

Reconfigure the API to segment its components into individual variables

I'm currently working with an API that offers a wide range of available calls. In my VUE code, I am looking to modify it so that depending on which button is clicked, a different call is triggered. You can check out one example of this here: <> ...

Tips for replicating input fields that fetch information via ajax requests

My current code fetches data using AJAX from the database and allows for adding an unlimited number of text fields: <div class="input" id="itemRows"> <div class="clone"> <style> .txtHint { width:95 ...

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...

Ways to automatically update React.js state when localStorage changes occur

Is it possible to automatically update the data on the cart page whenever there are changes made to the myCart array in localStorage? Below is the code that I am currently using: const [cart, setCart] = React.useState([]) React.useEffect(() => { se ...

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

I am currently working on a Node.js application generated with express-generator and am experimenting with integrating Primus websocket

Currently in the process of developing a nodejs app using express-generator. I'm facing an issue while trying to integrate the Primus websocket into my application. The issue arises when I do not include app.listen(port) in my app.js file, causing the ...

Creating a service function (constructor) in JavaScript

When working with AngularJs and calling a service method: app.service('nameService', function() { this.Service = function (){console.log('hello')} } You can then use this service (object) like so: nameService.Service() My question is, ...

Issue: failure of child element - the provided path is incorrect: "users/[object Object]", when implementing Firebase with Next.js

Having trouble with the identityNumber variable, which is giving an error message stating that a string is required. However, my identity number is already a string. Any assistance would be greatly appreciated. Additionally, the aim is to make the identity ...