Count checked checkboxes


#1

Can anyone help me with this. I usually work on backend so I am stuck with this. I have three checkboxes in form, all with different names. HTML looks like this

  <form (ngSubmit)="postNumbers(f)" #f="ngForm">
    <ion-grid>
      <ion-row>
        <ion-col>
          <ion-item>
            <ion-label>1</ion-label>
            <ion-checkbox color="danger" name="number_one" ngModel="{{ x }}"></ion-checkbox>
          </ion-item>
        </ion-col>
        <ion-col>
          <ion-item>
            <ion-label>2</ion-label>
            <ion-checkbox color="danger" name="number_two" ngModel="{{ x }}"></ion-checkbox>
          </ion-item>
        </ion-col>
        <ion-col>
          <ion-item>
            <ion-label>3</ion-label>
            <ion-checkbox color="danger" name="number_three" ngModel="{{ x }}"></ion-checkbox>
          </ion-item>
        </ion-col>
      </ion-row>
    </ion-grid>
<ion-row>
      <ion-col class="signup-col">
        <button ion-button class="submit-btn" full type="submit" [disabled]="!f.valid">Post</button>
      </ion-col>
    </ion-row>
 </form>

Value for x in ngModel is false. Now my problem is even when checkboxes are unchecked my submit button isn’t disabled. Can anybody explain me how can I enable button only when two checkboxes are checked?


#2

See: http://masteringionic.com/blog/2017-01-28-validating-multiple-checkboxes-with-ionic/


#3

This is ok when I want to save all values in one column in database because this is example for array. I used this with json_decode in PHP but I can’t do it this way.


#4

The ion-checkbox does not automatically trigger Angular’s change detection. You can’t mix a form function with checkboxes without extra work. As a start, have the ion-change function of each checkbox call ChangeDetectorRef.detectChanges()., I would roll my own validity function though, instead of relying on Angular’s.


#5

I will try to do validation in backend.