Akshat Sharma
Akshat Sharma

Reputation: 41

How to get state of input field by clicking at parent <label> element?

I have an input checkbox field inside a label tag in html with bootstrap 4 and Angular 7. And i am calling a function on click on input checkbox and passing its state "($event.target.checked)" as one of the arguments. But all i receive is "undefined". On other hand if i call the function directly from input:checkbox i.e. without tag ass the parent element then it works perfectly fine. But i need the former option to work.

Case 1: ">div>

label (click)="onChange('father', $event.target.checked, 'diabetes')" class="btn btn-sm rounded-pill position-relative mb-2 mx-2"> input type="checkbox" name="diabetes" autocomplete="off"> Father /label "

Case 2: ">div>

input type="checkbox" (click)="onChange('father', $event.target.checked, 'diabetes')" name="" id="">Father /div>"

When i console both the above in my function, i receive undefined in 1st case with label outside the input field and it works just fine without label as shown in case 2 and provides true and false as results. Can anyone help me to get true and false values in case 1 also.

Upvotes: 2

Views: 552

Answers (1)

user4676340
user4676340

Reputation:

That's because you listen to click eventd on your checkbox.

Intsead, you should listen to (change) event :

(change)="onChange('father', $event, 'diabetes')" 

This way, the function will be called everytime the value of the checkbox changes.

Upvotes: 0

Related Questions