"Upon triggering an event in AngularJS, the data attribute transitions to a state of truth

Here is the input I am using:

<input type="checkbox" ng-model="area.id" data-id="{{area.id}}"/>

Above this, there is some action with ng-click functionality. My goal is to gather all selected checkboxes' ids. However, after checking them, the value of the data-id attribute changes to true/false. Why does this happen?

The function in the controller looks like this:

collectSelectedAreas($event) {
    let selectedArea = $event.currentTarget.querySelectorAll('input:checked');
    let areaIds = [];

    [selectedArea].forEach((el) => {
        console.log(el.attributes['data-id'].value);
    });
}

Answer №1

Option 1:

If you wish, you can choose an alternative method to keep track of the checkbox value (true/false). See the code snippet below:

<input type="checkbox" ng-model="area.selected" data-id="{{area.id}}"/>

In this scenario, when the checkbox is selected, area.selected = true

Next, within your function, loop through your array of areas. Let's assume you have an arrayOfAreas, the same array being iterated in your ng-repeat

collectSelectedAreas() {    
    let areaIds = [];

    arrayOfAreas.forEach((el) => {
        if (el.selected){
           areasId.push(el);//Add selected element to array
           console.log(el.id);
        }
    });
}

Option 2:

<input type="checkbox" ng-model="area.selected" data-id="{{area.id}}" ng-true-value="area.id" ng-false-value="'NO'"/>

This setup ensures that when the checkbox is checked, area.selected will hold the value of area.id, otherwise it will be 'NO';

Answer №2

To determine if a checkbox is selected, you do not need to access the DOM. Instead, you can simply check the model value area.id. If the value is true, then the checkbox is selected. You can then navigate through the area object to find the key that identifies the id of the selected checkbox. For example:

<input type="checkbox" ng-model="area.id" />

where

$scope.area.id==true if checkbox is selected.

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

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

Navigating with relative URLs using RouteProvider in AngularJS

I have been working on a website that I plan to host in a directory within IIS. While testing the application locally with IISExpress, I noticed that the routes are relative to the base URL, allowing me to define them easily like this: $routeProvider.when ...

Dynamically retrieving markers from the database based on the most recent timestamp of the last loaded batch

I currently have a database where I store marker locations along with their latitude, longitude, type, and timestamp. Right now, my code loads all markers from the database and displays them on the map with different icons based on their type. However, w ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

Issues with locating Angular JS Text Area using Selenium Locator

Can you recommend a method for identifying the text area in a web application? <div contenteditable="true" id="taTextElement9662867992554610" ta-bind="ta-bind" ng-model="html" placeholder="Enter Role Requirements" class="ng-isolate-scope ng-pristine n ...

Steps for extracting a portion of the current page's URL

Can someone help me extract a specific part of the current URL using JavaScript? The URL looks something like this: I need to isolate the number "3153038" from the URL and store it in a JavaScript variable. Thank you! ...

another option besides the nextElementSibling

I have a unique code that applies a style to the following div when another div is clicked, using nextElementSibling. var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("clic ...

Is there a way to toggle the slide effect of one 'div' without affecting another one?

Hey everyone! I am new to jquery and currently working on a project with two div elements that are slidetoggled. The issue I am facing is that when I open or close one div, the other div also moves along with it. I understand what is happening in the back ...

Traverse through a collection of objects

I am facing a challenge with an array of objects (~650) structured like this: [1: {firstName: "Hello", lastName: "World", shortName: "h.world", ...some other items }, 2: {firstName: "John", lastName: "Doe", shortName: "j.doe", ...some other items }] ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

The outcome of the function is showcased within the home view blade of the controller in Laravel using PHP

I am trying to display the total amount from the 'payments' table in the home view blade. Initially, I tested another method using a route which worked fine but displayed the result on /test page: Route::get('/test', function(){ $tot ...

iOS alert notification for navigator

How can I fix the issue with my alerts not working on my iOS project? I am using Ionic and AngularJS to develop my app. The problem I am facing is that when the alert pops up, the title shows as "index.html". This is how I call the alert: alert("aaa"); ...

What is the preferred way to handle return values in a JQuery Ajax function - true or

Just a quick question about my AJAX function - should I include return statements in the code? Here's an example for reference: $.ajax({ type: 'POST', url: 'Application.cfc?method=runProcess', data: {'userID' ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...

Prevent angular from being executed through a JavaScript function triggered by a button click

Here is a button: <button ng-click="deleteCompany(company.id)" class="btn btn-danger" onClick="return window.confirm('This will permanently delete the entity\n Are you sure you want to delete this post?'); "> <s ...

New feature in jQuery inputmask enables placeholder text to be retained

I have integrated the inputmask feature from https://github.com/RobinHerbots/jquery.inputmask in my project, and I am applying the mask to all textboxes with the class "date". However, I am encountering a problem where if the user leaves one or more letter ...

Initializing an array with custom types enclosed in curly braces

I'm facing difficulties in understanding why the code below is not functioning properly. There are three classes defined as follows: class VertexType { public: VertexType(void) {}; virtual ~VertexType() = 0; }; class PositionColorVertex : ...

Navigate back to the previous page following the completion of an AJAX data submission

When using ajax to send data from page A to the server, the spring controller returns welcome page B. This process works correctly on Firefox and Internet Explorer, but on Chrome, there is an issue where after successfully sending the data via ajax, the de ...

Comparing the map function and for loop in the Puppeteer package for Node.js

I experimented with the Puppeteer package in NodeJS and noticed a significant difference in functionality between using the map function versus a for loop. Here is an illustration of what I observed: Using the map function: data.map(async(info) =>{ ...