[英]How to add multiple selected checkbox values to an array using Javascript?
I have an input element being populated using the *ngFor loop fetching the data from another array.我使用 *ngFor 循环填充了一个输入元素,该循环从另一个数组中获取数据。 On selecting multiple checkboxes, I need their values to be pushed into my empty array 'selectedArr'.
在选择多个复选框时,我需要将它们的值推送到我的空数组“selectedArr”中。 Find below the code:
在代码下方找到:
import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { title = "CodeSandbox"; toDo = ["Test", "Eat", "Sleep"]; task: string; addTask(task: string) { this.toDo.push(task); } selectedArr = []; deleteValue() {} addSelected(i) { let checkId = document.getElementsByClassName("i"); console.log(checkId); if (checkId.checked === true) { this.selectedArr.push(i); } console.log(this.selectedArr); } }
<div> <div class="form-group"> <label>Add a Task: </label> <input class="form-control" type="text" [(ngModel)]="task" /> </div> <button (click)="addTask(task)">Add</button> <br /> <br /> <div> My To Do List: <ul> <li *ngFor="let todo of toDo, index as i"> <input class="i" type="checkbox" (click)="addSelected(i)" /> {{todo}} </li> </ul> </div> <div class="btn class"> <button class="btn btn-primary" (click)="deleteValue()">Delete</button> </div> </div>
Try like this:像这样尝试:
.html .html
<li *ngFor="let todo of toDo, index as i">
<input class="i" type="checkbox" [(ngModel)]="checked[i]" (ngModelChange)="addSelected(todo,$event)" />
{{todo}}
</li>
.ts .ts
checked = []
selectedArr = [];
addSelected(item,evt) {
if (evt) {
this.selectedArr.push(item);
}else {
let i = this.selectedArr.indexOf(item)
this.selectedArr.splice(i,1)
}
}
The getElementsByClassName
method of Document
interface returns an array-like object of all child elements which have all of the given class name(s). Document
接口的getElementsByClassName
方法返回具有所有给定类名的所有子元素的类数组对象。 Since you are passing the index, you can access the clicked element like:由于您正在传递索引,因此您可以访问单击的元素,例如:
addSelected(i) {
let checkId = document.getElementsByClassName("i")[i];
console.log(checkId);
if (checkId.checked) {
this.selectedArr.push(i);
} else {
// Remove the index from selectedArr if checkbox was unchecked
let idx = this.selectedArr.indexOf(i)
if (idx > -1) this.selectedArr.splice(idx, 1)
}
console.log(this.selectedArr);
}
please, the things easy works easy.拜托,容易的事情很容易。 You needn't actually manually the array.
您实际上不需要手动创建数组。 You should use a function (*)
你应该使用一个函数 (*)
get selectedArray()
{
return this.toDo.filter((x,index)=>this.checked[index])
}
<li *ngFor="let todo of toDo, index as i">
<!--remove (ngModelChange) -->
<input class="i" type="checkbox" [(ngModel)]="checked[i]" />
{{todo}}
</li>
{{selectedArray}}
(*) this allow you "start" the app with some selected (*) 这允许您“启动”应用程序并选择一些
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.