Petros Kyriakou
Petros Kyriakou

Reputation: 5343

How to disable submit button when form is empty

I am using Angular2 and i want to disabled the submit button until all fields have something in them, i tried the following but it does not work.

import {Component, ViewEncapsulation} from "angular2/core";
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, AbstractControl, Validators, Control} from "angular2/common";

@Component({
    selector: "parameters-form",
    directives: [FORM_DIRECTIVES],
    encapsulation: ViewEncapsulation.None,
    styleUrls: [
      "app/css/main.css"
    ],
    template: `

      <div class="ui grid">
        <div class="eleven wide column">
          <h1>Parameters Form</h1>
          <form [ngFormModel]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="ui form">

            <div class="two fields">
              <div class="field">
                <label for="numberOfModelParameters">Number of Model Parameters(n)</label>
                <input type="number" #n
                       id="numberOfModelParameters"
                       placeholder="numberOfModelParameters Param"
                       [ngFormControl]="myForm.controls['numberOfModelParameters']">
              </div>
              <div class="field">
                <label for="numberOfModelVariables">Number of Model Variables(m)</label>
                <input type="number" #m
                       id="numberOfModelVariables"
                       placeholder="numberOfModelVariables Param"
                       [ngFormControl]="myForm.controls['numberOfModelVariables']">
              </div>
            </div>

            <div class="two fields">
              <div class="field">
                <label for="systemParameters">System Parameters</label>
                <input type="number"
                       id="systemParameters"
                       placeholder="systemParameters Param"
                       [ngFormControl]="systemParameters"
                       (keypress)="addToArray($event, systemParameters.value, 'systemParameters')">
              </div>
              <div class="field">
                <label for="restrictOperator">Restrict Operator</label>
                <input type="number"
                       id="restrictOperator"
                       placeholder="restrictOperator Param"
                       [ngFormControl]="myForm.controls['restrictOperator']"
                       (keypress)="addToArray($event, restrictOperator.value, 'restrictOperator')">
              </div>
            </div>

            <div class="two fields">
              <div class="field">
                <label for="param">Param</label>
                <input type="number"
                       id="param"
                       placeholder="param"
                       [ngFormControl]="myForm.controls['param']"
                       (keypress)="addToArray($event, param.value, 'param')">
              </div>
              <div class="field">
                <label for="liftOperator">Lift Operator</label>
                <input type="number"
                       id="liftOperator"
                       placeholder="liftOperator Param"
                       [ngFormControl]="myForm.controls['liftOperator']"
                       (keypress)="addToArray($event, liftOperator.value, 'liftOperator')">
              </div>
            </div>

            <div class="two fields">
              <div class="field">
                <label for="netLogoFile">Net Logo File</label>
                <input type="number"
                       id="netLogoFile"
                       placeholder="netLogoFile Param"
                       [ngFormControl]="myForm.controls['netLogoFile']">
              </div>

              <div class="field">
                <label for="xInitial">xInitial</label>
                <input type="number"
                       id="xInitial"
                       placeholder="xInitial Param"
                       [ngFormControl]="myForm.controls['xInitial']"
                       (keypress)="addToArray($event, xInitial.value, 'xInitial')">
              </div>
            </div>


            <div class="field">
              <label for="realisations">Realisations</label>
              <input type="number"
                     id="realisations"
                     placeholder="Realisations Param"
                     [ngFormControl]="myForm.controls['realisations']">
            </div>

            <div class="field">
              <label for="NumConstSteps">Number of Constant Steps</label>
              <input type="number"
                     id="NumConstSteps"
                     placeholder="NumConstSteps Param"
                     [ngFormControl]="myForm.controls['numConstSteps']">
            </div>

            <div class="field">
              <label for="timeHorizon">Time Horizon</label>
              <input type="number"
                     id="timeHorizon"
                     placeholder="timeHorizon Param"
                     [ngFormControl]="myForm.controls['timeHorizon']">
            </div>

            <div class="field">
              <label for="continuationStep">Continuation Step</label>
              <input type="number"
                     id="continuationStep"
                     placeholder="continuationStep Param"
                     [ngFormControl]="myForm.controls['continuationStep']">
            </div>

            <div class="field">
              <label for="continuationStepSign">Continuation Step Sign (+,-)</label>
              <input type="text"
                     id="continuationStepSign"
                     placeholder="continuationStep sign"
                     [ngFormControl]="myForm.controls['continuationStepSign']">
            </div>


            <button [disabled]="!isFullfilled(m.value, n.value) && !myForm.valid" type="submit" class="ui button">Submit</button>
          </form>
        </div>
        <div class="five wide column">
          <div class="parameter-values-display">
            <pre>{ System } parameters</pre>
            <li class="parameters" *ngFor="#sa of system_arr">
              <p>{{ sa }}</p>
              <button class="destroy" type="button" (click)="deleteItem(a, 'systemParameters')"></button>
            </li>

            <pre>{ Param } Parameters</pre>
            <li class="parameters" *ngFor="#pa of param_arr">
              <p>{{ pa }}</p>
              <button class="destroy" type="button" (click)="deleteItem(a, 'param')"></button>
            </li>

            <pre>{ Restrict Operator } parameters</pre>
            <li class="parameters" *ngFor="#ra of restrict_arr">
              <p>{{ ra }}</p>
              <button class="destroy" type="button" (click)="deleteItem(a, 'restrictOperator')"></button>
            </li>

            <pre>{ Lift Operator } parameters</pre>
            <li class="parameters" *ngFor="#la of lift_arr">
              <p>{{ la }}</p>
              <button class="destroy" type="button" (click)="deleteItem(a, 'liftOperator')"></button>
            </li>

            <pre>{ xInitial } parameters</pre>
            <li class="parameters" *ngFor="#xa of xinitial_arr">
              <p>{{ xa }}</p>
              <button class="destroy" type="button" (click)="deleteItem(a, 'xInitial')"></button>
            </li>
          </div>
        </div>
      </div>

    `
})
export class ParametersForm {
  myForm: ControlGroup;

  systemParameters: AbstractControl;
  param: AbstractControl;
  liftOperator: AbstractControl;
  restrictOperator: AbstractControl;
  xInitial: AbstractControl;

  system_arr: number[];
  param_arr: number[];
  restrict_arr: number[];
  lift_arr: number[];
  xinitial_arr: number[];

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      "realisations" : ["", Validators.required],
      "numConstSteps" : ["", Validators.required],
      "timeHorizon": ["", Validators.required],
      "continuationStep" : ["", Validators.required],
      "continuationStepSign" : ["", Validators.required],
      "numberOfModelParameters" : ["", Validators.required],
      "systemParameters" : [""],
      "param" : [""],
      "netLogoFile" : ["", Validators.required],
      "numberOfModelVariables" : ["", Validators.required],
      "restrictOperator" : [""],
      "liftOperator" : [""],
      "xInitial" : [""]

    });
    this.system_arr = [];
    this.param_arr = [];
    this.restrict_arr = [];
    this.lift_arr = [];
    this.xinitial_arr = [];
    this.param = this.myForm.controls["param"];
    this.systemParameters = this.myForm.controls["systemParameters"];
    this.restrictOperator = this.myForm.controls["restrictOperator"];
    this.liftOperator = this.myForm.controls["liftOperator"];
    this.xInitial = this.myForm.controls["xInitial"];
  }
  addToArray(event, value: number, target: string): void {
    if (event.which === 13 && typeof value === "number") {

      switch (target) {
        case "systemParameters":
          this.system_arr.push(value);
          (<Control>this.systemParameters).updateValue("");
          break;
        case "param":
          this.param_arr.push(value);
          (<Control>this.param).updateValue("");
          break;
        case "liftOperator":
          this.lift_arr.push(value);
          (<Control>this.liftOperator).updateValue("");
          break;
        case "restrictOperator":
          this.restrict_arr.push(value);
          (<Control>this.restrictOperator).updateValue("");
          break;
        case "xInitial":
          this.xinitial_arr.push(value);
          (<Control>this.xInitial).updateValue("");
          break;

      }
    }
  }

  deleteItem(value: any, target: string): void {
    let pos = 0;
    switch (target) {
      case "systemParameters":
        pos = this.system_arr.indexOf(value);
        this.system_arr.splice(pos, 1);
        break;
      case "param":
        pos = this.param_arr.indexOf(value);
        this.param_arr.splice(pos, 1);
        break;
      case "liftOperator":
        pos = this.lift_arr.indexOf(value);
        this.lift_arr.splice(pos, 1);
        break;
      case "restrictOperator":
        pos = this.restrict_arr.indexOf(value);
        this.restrict_arr.splice(pos, 1);
        break;
      case "xInitial":
        pos = this.xinitial_arr.indexOf(value);
        this.xinitial_arr.splice(pos, 1);
        break;

    }
  }

  isFullfilled(m: number, n: number) {
    console.log( `here is m:${m} and here is n:${n}`);
    console.log(`here is restrict array: ${this.restrict_arr.length}`);
    console.log(`here is xinitial array: ${this.xinitial_arr.length}`);
    console.log(`here is param array: ${this.param_arr.length}`);
    console.log(`here is system array: ${this.system_arr.length}`);
    console.log(`here is lift array: ${this.lift_arr.length}`);

    if (
          m == this.restrict_arr.length
          && m == this.xinitial_arr.length
          && m == this.lift_arr.length
          && n == this.param_arr.length
          && n == this.system_arr.length
       ) {
         if (m != 0 && n != 0){
           console.log("returned true");
           return true;
         }
       }

       return null;
  }
  onSubmit(form: any): void {
    form.systemParameters = this.system_arr;
    form.liftOperator = this.lift_arr;
    form.restrictOperator = this.restrict_arr;
    form.param = this.param_arr;
    form.xInitial = this.xinitial_arr;

    console.log("your submitted value:", form);
  }

}

I have used Validators.required and put [disabled]=!myForm.valid but does not seem to work, i have 5 fields though that do not need any value in them because i push their values into respective arrays by pressing enter on their respective fields.

here is a plunker

Upvotes: 1

Views: 971

Answers (3)

Sasxa
Sasxa

Reputation: 41254

It should work if you make isFullfilled a getter plunker

<button [disabled]="!isFullfilled || !myForm.valid" type="submit" class="ui button">Submit</button>

  get isFullfilled() {
    let m: number = this.myForm.controls["numberOfModelVariables"].value;
    let n: number = this.myForm.controls['numberofModelParameters'].value;

    if (
          m == this.restrict_arr.length
          && m == this.xinitial_arr.length
          && m == this.lift_arr.length
          && n == this.param_arr.length
          && n == this.system_arr.length
       ) {
         if (m != 0 && n != 0){
           console.log("returned true");
           return true;
         }
       }

       return null;
  }

Upvotes: 1

Petros Kyriakou
Petros Kyriakou

Reputation: 5343

Ok it seems i found the mistake i made.

it lies within this line

<button [disabled]="!isFullfilled(m.value, n.value) && !myForm.valid" type="submit" class="ui button">Submit</button>

in particular this part of the code

"!isFullfilled(m.value, n.value) && !myForm.valid"

this meant that if isFullfilled returns true in its function and gets converted to false and !myForm.valid returned either true OR false [disabled] directive only saw this as false because

true && false => returns false

so the button got enabled either way

true || false => returns true

which let the button be disabled until all conditions are met.

Changing it to use OR ( || ) got the job done.pretty tricky one. I will leave this here for future reference.

Upvotes: 0

Jorel Amthor
Jorel Amthor

Reputation: 1294

you could add a onChange method on your form ( not sure about the syntax but the principle still the same )

<form [ngFormModel]="myForm" (ngChange)="checkFields()" (ngSubmit)="onSubmit(myForm.value)" class="ui form">

function checkFields(){
    inputs = document.getElementsByTagName("input");
    isEveryInputFilled = true;
    for(input in inputs){
        if(input.value == null || input.value == "")
           isEveryInputFilled = false;

    }
}

Upvotes: 1

Related Questions