Reset forms on angular 2 - javascript

im trying to get some values in forms using the submit event. But i can´t reset those forms later. Im trying to use an id called "myForm" and an onclick function
<form (Submit)="addMarker()" id="myForm">
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary" onclick="myFunction()">Agregar Marcador</button>
</div>
</div>
</form>
Script:
function myFunction() {
document.getElementById("myForm").reset();
}

In your HTML:
<form (submit)="addMarker(myForm)" id="myForm" #myForm="ngForm"> // <-- Notice the "#"
<div class="row">
<div class="col">
<input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
</div>
<div class="col">
<input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
</div>
<div class="col-3">
<button type="submit" class="btn btn-primary">Agregar Marcador</button>
</div>
</div>
</form>
In your ts:
Import NgForm first by adding:
import { NgForm } from '#angular/forms';
Function to reset the form:
addMarker(form: NgForm) {
//do something and then reset the form
form.resetForm();
}

For Angular 2 Final, we now have a new API that cleanly resets the form:
#Component({...})
class App {
form: FormGroup;
...
reset() {
this.form.reset();
}
}
This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

Related

Changing div inner HTML content by id in angular component method

I am trying to change inner HTML content of a div by id with another div in angular component method. I am able to call populateEndpointHomeContent() and get that content but not further content. Actually those methods populateAddEndpoint() and populateAddEndpointForm are not getting called on click. I am not getting any console error also. Any idea how I can get this?
endpoint.component.html
<div id="endpoint_home"></div>
<div id="endpoint_home_content" style="display:none">
<button class="btn btn-sm" (click)="populateAddEndpoint();">+ Add Endpoint</button>
</div>
<!-- Add Endpoint DIVS Starts -->
<div id="add_endpoint_home" style="display:none">
<form #endpointForm="ngForm">
<section class="form-block">
<div class="form-group">
<label for="endPointType">Select Endpoint Type</label>
<div class="select">
<select id="endPointType" (change)="populateAddEndpointForm(this.value);">
<option>MACHINE</option>
<option>K8S_CLUSTER</option>
<option>AWS</option>
<option>DOCKER</option>
<option>VCENTER</option>
<option>WAVEFRONT</option>
<option>VRNI</option>
</select>
</div>
</div>
<div id="add_endpoint_form"></div>
<button type="submit" class="btn btn-primary">ADD</button>
</section>
</form>
</div>
<div id="add_machine_form" style="display:none">
<div class="form-group">
<label for="name">Endpoint Name</label>
<input type="text" placeholder="Endpoint Name" size="42" id="name" name="name" [(ngModel)]="name" required>
</div>
<div class="form-group">
<label for="credentialsName">Credential Name</label>
<div class="select">
<select id="credentialsName">
<option>MACHINE</option>
</select>
</div>
</div>
<button type="button" class="btn btn-primary">ADD CREDENTIAL</button>
<div class="form-group">
<label for="host">Machine Host/IP</label>
<input type="text" placeholder="0.0.0.0" size="42" id="host" name="host" [(ngModel)]="host" required>
</div>
<div class="form-group">
<label for="sshPort">SSH Port</label>
<input type="number" placeholder="22" size="42" id="sshPort" name="sshPort" [(ngModel)]="sshPort" required>
</div>
<div class="form-group">
<label for="timeout">SSH Timeout</label>
<input type="number" placeholder="60" size="42" id="timeout" name="timeout" [(ngModel)]="timeout" required>
</div>
<div class="form-group">
<label for="osType">OS Type</label>
<div class="select">
<select id="osType">
<option>WINDOWS</option>
<option>LINUX</option>
</select>
</div>
</div>
</div>
<!-- Add Endpoint DIVS Ends -->
EndpointComponent
import { Component, OnInit } from '#angular/core';
import { EndpointService } from './endpoint.service';
#Component({
selector: 'app-endpoint',
templateUrl: './endpoint.component.html',
styleUrls: ['./endpoint.component.scss']
})
export class EndpointComponent implements OnInit {
constructor(private endpointService: EndpointService) { }
public wavefrontendpoints: any;
ngOnInit() {
this.populateEndpointHomeContent();
this.endpointService.getAllEndpoints().subscribe(res => this.wavefrontendpoints = res.response[0]);
}
public populateEndpointHomeContent() {
document.getElementById('endpoint_home').innerHTML = document.getElementById('endpoint_home_content').innerHTML;
}
public populateAddEndpoint() {
console.log('Inside populateAddEndpoint...');
document.getElementById('endpoint_home').innerHTML = document.getElementById('add_endpoint_home').innerHTML;
}
public populateAddEndpointForm(endPointType) {
console.log('Inside populateAddEndpointForm...');
if(endPointType === 'MACHINE') { document.getElementById('add_endpoint_form').innerHTML = document.getElementById('add_machine_form').innerHTML; }
}
}
Trying to render HTML content from its innerHTML will not have its prototype functions work.
Your HTML will be visible, but it won't make their click events trigger, because innerHTML only contains the HTML markup, not the function or event prototypes.
Go through Angular's Guide on Dynamic Component Loader, which is about loading dynamic content in an HTML page.

Submit Button does not work / react

I am new to Angular 2 and Typescript but I am trying to build a web app.
I build some input fields and I want to log them to the console after submitting them via a button. But my button does not really work or react.
Does anyone have an idea what is the problem with my code?
Here is my code:
app.component.html
<div class="panel panel-primary">
<div class="panel-heading">Status</div>
<div class="panel-body">
<h3>{{title}}</h3>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control" name="street" ngModel>
</div>
<div class="form-group">
<label>PLZ</label>
<input type="text" class="form-control" name="plz" ngModel>
</div>
</form>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
app.component.ts
import { Component, style } from '#angular/core';
import { TutorialsComponent } from './tutorial.component';
import { SteliosComponent } from './stelios.component';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public title ="Das ist die erste Componente"
public childData: string;
onSubmit(value: any){
console.log(value);
}
}
Your button isn't in your form. Put it in your form and you're good to go !
You have to associate the submit button with the form.
This is usually done by putting the <button> element inside the <form> element.
You could do that by moving it to just before </form>.
Alternatively, you could use the form attribute:
<button form="id_of_form_element_goes_here" type="submit" class="btn btn-primary">Submit</button>
… but browser support for that is weaker.
Move the submit button inside the form.
<form>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

send input data with onsubmit method

I have a Multi forms that contain some inputs
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" onsubmit="completeSave()">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
I want to get value of inputs on submitting form I tried this code but it didnt worked
function completeSave() {
event.preventDefault();
var thisForm = $(this);
console.log(thisForm.find('input[name="name"]').val())
}
it returns undefined in console
you are using jQuery for this case.
You need to import your jQuery then use below function
jQuery can be found at
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
function completeSave(e) {
event.preventDefault();
var thisForm = $(e).find("[name=name]");
console.log(thisForm.val());
}
FORM
<form class="form" role="form" onsubmit="completeSave(this)"> <!-- add this -->
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
use this java script code
function completeSave() {
event.preventDefault();
console.log($("#name").val());
}
but add an id on text input as -
<input type="text" class="form-control" name="name" id="name"
value="{{$media->name}}">
HTML forms
<form class="form" role="form" id="form1">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="button" id="{{$media->id}}" class="btn blue" onclick="completeSave("form1");">ارایه</button>
</div>
Scripts
function completeSave(formId) {
console.log($("#"+formId+' input[name="name"]').val())
}
Hope it helps :)
fist i assume you are using jquery
solution 1
the keyword this only evaluates to the form if the completeSave function
is called via jquery's submit event, so for this solution, you don't need the completeSave function on the form's HTML tag
$('form').submit(function(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
})
solution 2
you should pass the event argument to the completeSave function located on onsubmit attribute of form's HTML tag
ex: <form onsubmint="completeSave(event)">
since the this keyword doesn't evaluate to the form, you gotta select it manually
function completeSave(event) {
event.preventDefault();
var thisForm = $(event.target);
console.log(thisForm.find('input[name="name"]').val())
}
and the input[name="name"] will be the one whos form is submited
Please try this one:
For sure you should add unique id to your forms
<form class="form" role="form" id="form1" onsubmit="completeSave(form1)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
<form class="form" role="form" id="form2" onsubmit="completeSave(form2)">
<div class="form-body">
<div class="form-group">
<label>نام محتوا</label>
<input type="text" class="form-control" name="name"
value="{{$media->name}}">
</div>
<div class="form-actions">
<button type="submit" id="{{$media->id}}" class="btn blue">ارایه</button>
</div>
</form>
and your javascript code could look like this:
function completeSave(form) {
event.preventDefault();
var input = $("#" + form + " :text");
console.log(input.val());
}

Detect the name of required field and not validated when submit a form

I create a form in html5 like this example :
<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
$('form').submit(function(){
console.log('test');
});
</script>
The problem :
I want to detect the name of the required field that are not validated when submiting and logging it.
for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."
is there a way to do this ?
thank you.
Here you go.. Loop through each input:required field and get its name with .attr.
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
console.log($(this).attr('name'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Updated
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
if($(this).val()==""){ //check if its empty
console.log($(this).attr('name'));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..
Select them by property required:
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
console.log($(this).attr("name"));
});
});
});
To do a simple required check on your own make a simple "not empty" condition. But for this, your form need the novalidate class, otherwise submit callback will not be triggered and nothing ever happens.
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
if( $(this).val() != "" )
console.log($(this).attr("name"));
});
});
});
Full example here: https://jsfiddle.net/vvdh66rb/
You can also do like this:
<form action="/my/url/insert.php" method="POST" onSubmit="return myFunction()">
<div class="row">
<!--I am only giving id to one to show an exmaple you can give to differnt-->
name <input name="name" id="some" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
function myFunction() {
var x = document.getElementById('some').value;
if (x == "" || x == null) {
alert('sadsd');
return false;
//You can give anything else than alert
}
}

ng-repeat causes form elements to not display

I am trying to dynamically add a form input in AngularJS every time the add button is clicked. However, with the code I have, it the input elements don't display at all. I simply see the "Post" button. If I remove the ng-repeat="ingredient in ingredients", the form displays (as expected). What am I doing wrong here?
Here is the specific code in index.ejs:
<form ng-model="recipe">
<div class="form-inline" ng-repeat="ingredient in ingredients">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" ng-model="ingredient.name"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Quantity" ng-model="ingredient.quantity"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Unit" ng-model="ingredient.unit"></input>
</div>
<div class="form-group">
<button type="button" id="add" ng-click="add()">Add</button>
</div>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
Here is the corresponding js code:
app.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
$scope.ingredients = [];
$scope.add = function() {
var newItemNo = $scope.ingredients.length+1;
$scope.ingredients.push({'id':'choice'+newItemNo});
};
}]);
That's because your button is in the ng-repeated element. ng-repeat repeats the HTML inside the element it is assigned to. Since you have no items in ingredients, nothing is rendered - including your button
Just move your button out of <div class="form-inline">.
Your add button is inside the ng-repeat, so it's never shown, so you can never populate the array, so it can't ever show. Does that make sense?
Try
<form ng-model="recipe">
<div class="form-inline" ng-repeat="ingredient in ingredients">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" ng-model="ingredient.name"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Quantity" ng-model="ingredient.quantity"></input>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Unit" ng-model="ingredient.unit"></input>
</div>
</div>
<div class="form-group">
<button type="button" id="add" ng-click="add()">Add</button>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>

Categories