Master Checkbox in HTML Table Not Functioning for Selecting/Deselecting All Items

https://i.sstatic.net/RKWaC.png

I'm facing an issue with my code that allows me to select and deselect multiple rows in a table. Specifically, I'm struggling with implementing a SELECTALL/DESELECTALL feature using a master checkbox.

You can view the reproduced version of my code at this URL: https://stackblitz.com/edit/angular-ivy-bbx9jh?file=src/app/app.component.ts

HTML

<div class="card-body">
<div class="table-responsive">
  <table  class="table">
      <thead class=" text-primary">
          <th>
             <input type="checkbox">
          </th>
          <th>
             Product Name
          </th>
          <th>
              Cost
          </th>
          <!-- <th>
              City
          </th>
          <th>
              Salary
          </th> -->
      </thead>
      <tbody>

          <tr *ngFor = "let data of productDataMultipleValue; let j = index;">
              <td>  
                <span style="padding-left:20px;
              ">             
          <input type="checkbox" [checked]="data.checker" 
    (change)="checkboxMultiplier(data,$event,j)"></span></td>
              <td >
                  <span style="padding-left:140px;
              ">{{data.namer}}</span>
              </td>
              <td>
                  <span style="padding-left:40px;
              ">{{data.coster}}</span>
              </td>
              <!-- <td>
                  {{}}
              </td>
              <td class="text-primary">
                 {{}}
              </td> -->
          </tr>

      </tbody>
      </table>
   </div>
   </div>

Now below you can find the Typescript part of my code

TS

saveMultiRows: any = [];
productDataMultipleValue: any = [
{"id":1,"namer":"wires","coster":25},
{"id":1,"namer":"pipes","coster":40},
{"id":1,"namer":"motors","coster":67},
{"id"1:"lights","coster":78},
{"id";1,"namer":"switches","coster":86}
]


checkboxMultiplier(rowObj: any,event: any,rowIndex: any) {


let temp = 
  {  "namer":rowObj.namer,
  "coster" : rowObj.coster}

  if (event.target.checked == true) {

 
   this.saveMultiRows.push(temp);

    } else if (event.target.checked == false) {

    for (let j = 0; j < this.saveMultiRows.length; j++ ){
    if (this.saveMultiRows[j].coster == rowObj.coster) {
      this.saveMultiRows.splice(j,1);
    }
    }     
    }

console.log(this.saveMultiRows);

}

The code can also be viewed at: https://stackblitz.com/edit/angular-ivy-bbx9jh?file=src/app/app.component.ts

Answer №2

To accomplish this task in theory, you need to attach an onclick EventListener to the topmost checkbox (the one designated for select/deselect all). The following pseudocode can guide you:

  • Trigger onclick on the topmost checkbox,
  • Select all checkboxes using jQuery method $("input:checkbox"),
  • Update the isChecked property of the topmost checkbox to incorporate all other checkboxes.

Although I am not well-versed in TypeScript, the same concept can be applied using JavaScript and jQuery:

$("#topCheckbox").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

Assuming that you will assign an id=topCheckbox to your primary checkbox intended for select/deselect functionality

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

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

When using Vue, the image element may not display the value stored in the object property

Excuse me for being new to Vue and struggling a bit. I'm attempting to display an image using a src that comes from an object property, which is retrieved from an array returned by data() I am not receiving any errors, but the icon is not appearing. ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

The find element will yield an empty result when using XPath contains with Text() method

When checking for Gender and Date in the assertion, it returns false and the IWebElement displays an empty string. This anomaly only occurs with Gender and Date, while the rest provide accurate results. CODE IWebElement actualname = BrowserHelper.WebDri ...

Creating page borders in print CSS for each individual page is a helpful way to enhance the visual appeal

I am facing an issue where I have a lengthy HTML document that is ready for printing, but I need to add borders to every page. I tried adding body { border:2px #666 solid; padding:5px; } in the CSS code, which looked good in the HTML view, but not in the p ...

Delete the final comma in a JSON file using JavaScript so that it can be utilized by a Vue application

Using Axios in my Vue app, I am consuming a JSON file. The field "country" contains trailing commas which are creating issues. Here is the structure of the JSON: "country": "spain,france," .... "country": " ...

Tips for adjusting the dimensions of a cube using keyboard shortcuts:

Adjusting the cube size involves keeping one face stationary while others move and change in position or dimension. The height, depth, and width must be expanded or contracted based on user input from the keyboard. I have managed to create a cube, but so ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

What is the best way to select a specific value from JSON (Webhook) Data?

I am looking for a way to extract and store a specific value from a JSON data into a variable. Specifically, I want to save the value of Name (John) in a variable like this: var name = "". I attempted using var name = data.Name but it is not wor ...

Alignment of inner div within the footer

I'm struggling to align my footer navigation inline with my footer title. Check out this code snippet to see what I've tried so far: https://jsfiddle.net/nkzsufov/ I experimented with using absolute and relative positioning: .footerNav { margi ...

Exploring TypeScript: Ensuring Compatibility of Types

Given two sets of TypeScript type definitions in string format: Set A: { a: string b: number } Set B: { a: string } Is there a way to programmatically determine if these two sets are compatible? In other words, can we assign variables defi ...

Ways to retrieve information from a request handler

Working with express, node, and handlebars, I've implemented this piece of code to manage POST requests. When a user hits the "add item" button, it captures their input for a city, fetches the weather data for that city using the Open Weather Map API, ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Generate unique avatars with a variety of predefined image sets

Instead of solving my problem, I am seeking guidance on it: I have a project to create an Avatar maker in C# using a vast collection of categorized images. The concept is simple, but I lack experience in image manipulation through code, so I need some ad ...

Can you explain the process of sending an AJAX request and managing it on a web server coded in C?

Could someone please provide an example of an AJAX request that retrieves a global variable stored on a webserver written in C? I am unfamiliar with JQuery and AJAX, so I would appreciate any guidance on how to accomplish this task. Thank you in advance ...

AngularJS is a framework that allows for the implementation of vertical synchronous

After successfully implementing horizontal synchronous scrolling, I am now trying to achieve vertical scrolling. If anyone can assist, that would be greatly appreciated. You can find the sample where horizontal synchronous scrolling works here. e.target.s ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

Having trouble parsing bytes from a protobuf message in JavaScript

In my current project, I am faced with the task of encoding and decoding bytes within a protobuf message using Javascript. It seems that working with strings is functional, but once I introduce bytes in the message definition, retrieving the data becomes a ...

Verify the existence of the linked page's href url

Is there an elegant way to verify if a hyperlink on a website directs to a page that returns an HTML 200 code? I'd like to give users the ability to input their own links in a model, but I also want to block any links leading to a 500 or 404 error pag ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...