Hide form on submit with Angular JS - javascript

Trying to wrap my head around some Angular items and working thru a tutorial to edit and learn.
Clicking the below button shows the below form. How do I reverse this once the form is submitted? Meaning hiding the form on submit until the button is clicked once more.
<button ng-click="addNewClicked=!addNewClicked;" class="btn btn-sm btn-primary">
<i class="fa fa-plus"></i>Add Task
</button>
Basically, the form appears, I enter something and submit, but would like the form to dissapear upon submit? Thinking something to do with ng-hide, but can I do this using only Angular? Or do I need to do something with javascript/css?
<div id="addForm" class="margin-full-5">
<form ng-init="addNewClicked=false; " ng-if="addNewClicked" id="newTaskForm" class="add-task">
<div class="form-actions">
<div class="input-group">
<input type="text" class="form-control" name="comment" ng-model="taskInput" placeholder="Add New Task" ng-focus="addNewClicked">
<div class="input-group-btn">
<button class="btn btn-default" type="submit" ng-click="addTask(taskInput)">
<i class="fa fa-plus"></i> Add Task
</button>
</div>
</div>
</div>
</form>

You can also achieve this using a combination of Angular form's attribute $submitted, ng-hide and ng-submit
<form name="myForm" ng-hide="myForm.$submitted" ng-submit="submit()">
<button>Submit</button>
</form>
Read about it here: https://docs.angularjs.org/api/ng/type/form.FormController

Somewhere in your view.
<button ng-click="showTheForm = !showTheForm">Add a Task</button>
<form ng-show="showTheForm" ng-submit="processForm()">
<button>Submit</button>
<button type="button" ng-click="showTheForm = false">Cancel</button>
</form>
Somewhere in your controller
$scope.processForm = function() {
// execute something
$scope.showTheForm = false;
}

Your form is displaying IF the addNewClicked value evaluates to true, which occurs when you click the add task button. If you want the form to disappear on submit, you just need to make the onClick to that button change your addNewClicked to false.
AngularJS Docs for Ng-If

You can do that by using ng-show/ng-hide as per example below :
<form ng-init="addNewClicked=false; " ng-if="addNewClicked" ng-hide="hideform" id="newTaskForm" class="add-task">
and modify the submit method to make the hideform = true;
$scope.addTask = function(input){
... your things
$scope.hideform = true;
}
You can also do the same using jQuery :
$("#newTaskForm").hide();

This should do the trick:
$scope.addTask = function(taskInput) {
...
$scope.addNewClicked = false;
}

You could use ng-show as you can see in this jsfiddle
This will show and hide the div element based on clicking the button. When the button is clicked it will toggle the boolean, hence acting as an on/off switch for ng-show

Related

Detecting return on input vs button click in reactive form

I'm building a reactive form in Angular with 3 submit buttons on it.
<form [formGroup]="sessionForm" (submit)="submitSession($event)">
<div class="row">
<label>
<span>Title</span>
<input type="text" formControlName="title" [class.required]="markRequired.indexOf('title') >= 0">
</label>
</div>
... more fields ...
<div *ngIf="!admin" class="row">
<button type="submit" (click)="setBtnClicked('submit')" class="btn btn-primary">Submit</button>
</div>
<div *ngIf="admin" class="row">
<button type="submit" (click)="setBtnClicked('save')" class="btn btn-primary">Save</button>
<button type="submit" (click)="setBtnClicked('approve')" class="btn btn-success">Save and approve</button>
<button type="submit" (click)="delete($event, false)" [hidden]="confirmDelete" class="btn btn-danger">Delete</button>
<button type="submit" (click)="delete($event, true)" [hidden]="!confirmDelete" class="btn btn-danger">Are you sure?</button>
</div>
<div [hidden]="!showSuccess" class="msgBox msgBox-success">Your session has been submitted! It will need to be approved before it is listed.</div>
</form>
On each button, I've attached a (click) handler which triggers a function to track which button is hit:
setBtnClicked(value) {
this.btnClicked = value;
}
However, when someone hits return on an input, I notice that the value of this.btnClicked is equal to the first button in the form.
I'm not sure how to track when a user hits return or when they hit the button, so I can respond differently, or if my structure is wrong. I'd like to trigger the submitSession function on any submit, be it return or button. I did try adding a formControl to the buttons, but that failed.
Because you're using a form, pressing enter on an input should run the submitSession() method tied to the form, but it's possible it's defaulting to the first submit button on the form. Maybe removing the submitSession() as well as the type="submit" from the buttons will prevent a form submission based on enter. That way the user would need to actually click a button to trigger something.
Also in the methods where you pass the event in, the following code would detect if it was triggered by an enter key press.
if (event.keyCode === 13) {
console.log('you just clicked enter');
}

Multiple submit buttons in angular2 form

I am building angular2 form and I would like to have multiple buttons to submit the form, e.g "Save" and "Save and close".
I have tried to use simple buttons with click action on them, but I didn't find anyway to manually mark form as submitted to force form validation.
<form #ticketForm="ngForm" novalidate>
<input type="text" id="customerName" required
name="customerName" [(ngModel)]="ticket.customerName"
#customerName="ngModel">
<div class="tj-form-input-errors"
*ngIf="customerName.errors && (customerName.dirty ||
customerName.touched || ticketForm.submitted)">
<small [hidden]="!customerName.errors.required">
Customer name is required
</small>
</div>
<button type="button" (click)="save(ticketForm)">Save</button>
<button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>
Assign different id to each button. Then you can obtain the id of the button which triggered submit using document.activeElement.id. like the following :
In your Html :
<form #form="ngForm" (submit)="firstSave(form,$event)">
...
<div class="form-group">
<input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
<input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
</div>
</form>
Then in your typescript :
firstSave(form: NgForm, $event: Event) {
var activeButton = document.activeElement.id; // document.activeElement?.id
if (activeButton == "submit-1") {
alert("you have clicked on submit 1");
}
if (activeButton == "submit-2") {
alert("you have clicked on submit 2");
}
}
StackBlitz Here.
You can subscribe to form changes, which I think will fire form validation.
I do something like this:
this.physicalForm.valueChanges
.map((value) => {
return value;
})
.filter((value) => this.physicalForm.valid)
.subscribe((value) => {
do what you need with the values here...
});
Then in your click handler for each button, if this.physicalForm.valid you save or save&update.
i ran into the same situation. In my case i have 2 submit 'Save','Save and Allocate'
Solution
You can simply set the the type of submit button in the payload and do the action accordingly in the backend code.
Sample code
//here formData is my payload for the API call eg: formData.name,formData.email
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='save'">Save</button>
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='allocate'">Save And Allocate</button>

isValid Form vaildation then run a function AngularJS

Just wondering if someone can please give me some pointers regarding running a function if an AngularJS form is Valid.
If the form is not valid then the errors appear but if the form is valid after clicking a submit button I would like it to move to the next step in the form (multistep form), so basically click of a button to validate, if valid it opens a new tab or an expandable etc.
Any pointers would be very much appreciated.
Kind regards,
You may do like this:
html:
<form name="myForm">
<div id="step1">
<button type="button" ng-click="nextStep(form, validateStepOne, 2)">Next step</button>
</div>
<div id="step2">...</div>
<div id="step3">...</div>
</form>
js:
function validateStepOne() {
// validate form one and return true or false
}
function nextStep(form, validation, nextStepIndex) {
if(form.$valid && validation()) {
// go to next step
}
}
you can try disabling the button if form is invalid like
<button (click)="submit()" [disabled]="!contactForm.form.valid" type="submit" class="btn btn-primary">Submit</button>
where form tag looks like
<form #contactForm="ngForm"> ...
or if you want to not disable the button and check valid from code maybe like
<button (click)="submit($event, contactForm)" class="btn btn-primary">Submit</button>
and on submit function
submit(event:any, contactForm:NgForm): void {
event.preventDefault();
if (contactForm.form.valid) {
...
}
}

Can't submit a form with JavaScript function when selecting radio input

I write this html code with mojolicius code mixed. The idea is to submit the form when I select a radio input that is stylized as a Bootstrap button.
If I put a submit type input, I select the Bootstrap button and I submit it, it works perfectly. But when I use this function (submitForm(node)) to submit the form, it seems to submit it, but is doesn't do anything. The Firefox debugger doesn't throw any error.
<form method="post" id="runform">
%if (keys %$base) {
%for my $option (sort keys %$base) {
<div class="col-sm-4">
<div class="panel panel-success machine">
...
<div class="btn-group pannel-body" data-toggle="buttons">
<label class="btn btn-success" id="base_action" onclick="submitForm(<%= $option %>)">
<input name="id_base" id="submit<%= $option %>" type="radio" value="<%= $option %>"><strong> <i class="fa fa-play" aria-hidden="true"></i> Start this Machine</strong>
</label>
</div>
</div>
</div>
%}
</form>
The JavaScript Function:
function submitForm(node) {
var id = "submit"+ node ;
document.getElementById(id).checked=true;
document.getElementById("runform").submit();
}
Thanks
You lack an action attribute on the form, so it gets submitted to the current page, that's why it seems to submit, but does nothing, because it's likely you have configured your server to just reply with the same page to the request.
Point the form to the right URL.

How to use ngModelOptions and $rollbackViewValue() in AngularJS 1.3

I have a problem with my input fields in my modal view.
When I take a change in the input fields then it is updating the table list but when I leave the page and go back to this page with the table list then die changes are disappeared.
This is my modal view:
<form class="form-horizontal" name="editForm" novalidate>
<div class="modal-body">
<div class="form-group-sm has-feedback">
<label class="control-label">Firstname</label>
<input type="text"
class="form-control"
name="Fname"
ng-model="selected.fname"
ng-model-options="{updateOn: 'updateItem'}"
ng-required="true"
/>
</div>
</div>
//the same input field for lastname
...
<div class="modal-footer">
<button class="btn btn-default" ng-click="createItem(selected)" type="submit">Erstellen</button>
<button class="btn btn-default" ng-click="updateItem(selected)"> Ă„ndern</button>
<button class="btn btn-default" ng-click="cancel()">Abbrechen</button>
</div>
</form>
Modal Ctrl:
$scope.cancel = function () {
$scope.editForm.$rollbackViewValue();
$modalInstance.dismiss('cancel');
}
$scope.updateItem = function (updateItem) {
CrudService.update(updateItem);
$scope.ok();
}
Crud Service:
...
update: function (updateItem) {
updateItem.$update();
},
...
I have only seen examples of $rollbackViewValue() with one input field and the code: $scope.myForm.inputName.$rollbackViewValue() but I have more than one input fields?
you should call $rollbackViewValue() through the form name:
editForm.$rollbackViewValue()
call it in your template:
{{editForm.$rollbackViewValue.toString()}}
and you will see how it actually works:
function () {
forEach(controls, function(control) {
control.$rollbackViewValue();
});
}
A little late but for others reference (I came across this looking for another issue with $rollbackViewValue).
Using $rollbackViewValue in controller: to use $scope to reference the form from the controller, you have to use the ng-form attribute on a child element of the form (like for instance the form-group div in your example).
That makes $scope.editForm.$rollbackViewValue() available in the controller and resets the entire form.
For cases where buttons are inside the form, using ng-submit and ng-model-options="{ updateOn: 'submit' }" on input fields, then adding 'type=button' attribute to cancel button element (so submit isn't triggered) is a quick solution.
Example:
https://embed.plnkr.co/IQ4vvutC3tcHvVBH0821/

Categories

Resources