QThompson
QThompson

Reputation: 1708

How do I pass values of checkboxes to a function in typescript?

I'm setting up a group of checkboxes that have values of different levels. Multiple levels can be selected and then submitted using the submit button. The submit button should then pass those values as parameters to a function in the typescript class.

I would like to pass the values as parameters. For example, if only level one and level two are selected the method and parameters would look like this:

levelSave(value1,value2)

Thanks in advance!

HTML

<div class="form-group">
   <li><input type="checkbox" id="level1" value="1" required><label for="level1"></label> Level 1 </li>
   <li><input type="checkbox" id="level2" value="2" required><label for="level2"></label> Level 2 </li>
   <li><input type="checkbox" id="level3" value="3" required><label for="level3"></label> Level 3 </li>
 </div>
    </ul>

<button type="button" class="green-btn pop-up-btn" (click)="levelSave()" id="LevelPopupSubmit">Submit</button> 

TypeScript

levels = [];


//value3 if level 3 was selected

levelSave(value1,value2){
  levels.push(value1);
  levels.push(value2);
}

Upvotes: 0

Views: 1276

Answers (2)

Prosenjit Manna
Prosenjit Manna

Reputation: 484

I am not sure you are using re-active form. You have added an angular tag. So, I giving a solution based on angular.

  • If you are not using a reactive form, you may see article https://angular.io/guide/reactive-forms
  • If you are using a reactive form, Checkbox is a form-control. So you can simply patch value. Or you can default check value.

Here is template

<input type="text" formControlName="checkedItem">
// Patch value
this.profileForm.patchValue({
    checkedItem: [false]
  });

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

You need to use Model variables here. Define an array of objects with 'Name','Checked' properties. Something like,

checkboxes = [{'name':'checkbox1',checked:false},{'name':'checkbox2',checked:false}];

and bind these to the form, so that when you want to get the checked checkboxes you could just pass those model variables to the function

Upvotes: 2

Related Questions