2

I have 8 to 10 checkboxes in my html. I need to send the checked checkboxes values to my typescript file.

<div>
    <input type="checkbox" value="one" id="one" name="num">
    <input type="checkbox" value="two" id="two" name="num">
    <input type="checkbox" value="three" id="three" name="num">
    <input type="checkbox" value="four" id="four" name="num">
</div>

How do I get all the selected checkboxes values in my ts file? Can somebody help me with this?

2
  • Are you using Reactive forms or Template driven forms, in your code nothing is there!!! Commented Aug 10, 2018 at 3:16
  • @Javascript Lover - SKT I'm using Reactive forms Commented Aug 10, 2018 at 6:54

1 Answer 1

1

You could use an array containing informations on your checkboxes, ngFor loop and ngModel:

checkboxes = [
    {
      value: 'one',
      selected: false
    },
    {
      value: 'two',
      selected: false
    },
    {
      value: 'three',
      selected: false
    },
    {
      value: 'four',
      selected: false
    }
  ]

Your html :

<div>
    <input *ngFor="let ch of checkboxes" [(ngModel)]="ch.selected" type="checkbox" value={{ch.value}} id={{ch.value}}  name="num">
</div>

<button (click)="getSelected()">Print selected checkboxes</button>

And the getSelected() function:

public getSelected() {
    let result = this.checkboxes.filter((ch) => { return ch.selected })
                     .map((ch) => { return ch.value });
    console.log(result);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.