Angularjs - How to submit a form from different controller? - javascript

<div ng-controller="ctrl1">
<form name="form1" ng-submit="submitForm()">
<input type="text" name="email" />
</form>
</div>
<div ng-controller="ctrl2">
<button> Submit </button>
</div>
Here from ctrl2, I want to trigger form submit action for a form which is in ctrl1
How to achieve this in angularJs?

You could emit an event on the button click and then use rootscope to broadcast it down - ctrl1 could then listen for this an submit the form in response.

You can achieve using $rootScope or services or event brodcasting
app.controller('ctrl2',['$scope','$rootScope',function($scope,$rootScope) {
$scope.submitForm = $rootScope.mainSubmit();
}]);
app.run(function($rootScope){
$rootScope.mainSubmit =function(){
console.log("hey");
};
})

You can emit an event from the second controller and listen to it in the first controller.
function CtrlOne($rootScope)
{
$rootScope.$on('submitEvent', function(event, args) {
//submit your form here
});
}
function CtrlTwo($scope,$rootScope)
{
$scope.submit=function(){
$rootScope.$emit('submitEvent', args);
}
}
<div ng-controller="CtrlOne">
<form name="form1" ng-submit="submitForm()">
<input type="text" name="email" />
</form>
</div>
<div ng-controller="CtrlTwo">
<button ng-click="submit()"> Submit </button>
</div>

Related

AngularJS form validation: show error message for checkbox after click on submit

With AngularJS, how can I show an error message for a checkbox after a click on submit button if the checkbox isn't checked?
I tried this :
<form action="/" method="post" name="myForm" novalidate>
<label>
<input type="checkbox" name="myCheckbox" ng-model="myCheckbox" value="1" required>
</label>
<p class="error" ng-show="myForm.$submitted && myForm.myCheckbox.$error.required">Error message</p>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
But it didn't work. When I click on submit button, nothing is happening. If I remove "novalidate" on form tag or "ng-disabled" on submit button, the form is submitted even if the checkbox is not checked.
Can you help me please ?
You have ng-disabled="myForm.$invalid" in your submit button, so the submit event never is fired (because the button is disabled when the form is invalid) and thus the condition ng-show="myForm.$submitted && myForm.myCheckbox.$error.required" never is fulfilled because myForm.$submitted is false.
Edit:
As some other users here have suggested, I think your best bet would be if you change the way you are doing things right now. I can think in tow solutions (very similar), but they includes sending the request "the angular way"
Solution 1:
Handle you form submission with angular like this:
Put in your form something like this (note that I deleted the action="/" method="post" part:
<form ng-submit="onSubmit(myForm)" name="myForm" novalidate>
and remove the ng-disabled="myForm.$invalid" from your submit button. Then it would be like this <button type="submit">Submit</button>
... and in the controller
$scope.onSubmit = function(form){
if(form.$invalid){
//... do your call to backend here as you like since the call directly from the form was removed
}
}
Solution 2:
As well change form like this: <form name="myForm" novalidate>
... change your submit button like this: <button type="submit" ng-click="onSubmit(myForm)">Submit</button>
... and use the same function declared in the controller
$scope.onSubmit = function(form){
if(form.$invalid){
//... do your call to backend here as you like since the call directly from the form was removed
}
}
Otherwise you have to change your condition like this
ng-show="myForm.myCheckbox.$error.required"
but this will show the message before the form is submitted
Remove myForm.$submitted because it is never fulfilled (As Asiel Leal mentioned) and also you have put ng-disabled on submit button, so safe to use.
<form action="/" method="post" name="myForm" novalidate>
<label>
<input type="checkbox" name="myCheckbox" ng-model="myCheckbox" value="1" required>
</label>
<p class="error" ng-show="myForm.$dirty && myForm.myCheckbox.$error.required">Error message</p>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
Try this working example :
var app = angular.module('myApp',[]);
app.controller('myController',function( $scope ) {
$scope.validate = function() {
alert('submitting..');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app= "myApp" ng-controller="myController">
<form name="myForm" ng-submit="myForm.$valid && validate()" novalidate>
<input type="checkbox" name="checkb" ng-model="formData.checkb" required/>
<span ng-show="submitted == true && myForm.checkb.$error.required">Please select the checkbox to proceed.</span>
<input type="submit" value="Submit" ng-click="submitted = true"/>
</form>
</div>

how to validate form using name or id attribute in angular Js

In form I have controls with name,id and class attribute. I cant add any costom attribute in html input element.
In this case how can I apply validation.
Can I write directive on element name or id?
HTML
<form class="form-horizontal text-center" role="form" name="DTOstep1" ng-submit="onSubmit(DTOstep1)" novalidate>
<input name="userinput1" id="userinput1" class="" />
<input name="userinput2" id="userinput2" class="" />
<input name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" />
</form>
directive code
(function () {
"use strict";
angular
.module("autoQuote")
.directive('userinput1', [userinput1])
....
Or is there any other way to do form validation. I wan to apply some custom validation to each form field.
The angular way requires the ng-model attribute to each field, in order to bind it with a model property.
function TestCtrl($scope) {
$scope.fields = {
"userinput1" : "Initial Value",
"userinput2" : ""
}
$scope.onSubmit = function onFormSubmit($event, form) {
if(form.$invalid) {
console.log("invalid", form);
event.preventDefault();
return;
}
console.log('valid', form);
//send here
};
}
angular
.module('test', [])
.controller("TestCtrl", ["$scope", TestCtrl])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<form name="DTOstep1" ng-submit="onSubmit($event, DTOstep1)">
<input name="userinput1" ng-model="fields.userinput1" required/>
<input name="userinput2" ng-model="fields.userinput2" required />
<input name="saveDto" type="submit" ng-disabled="DTOstep1.$pristine || DTOstep1.$invalid" />
</form>
</article>
</section>
by the way, if you can't edit the view in order to create an angular-form, you need to control the form via dom queries, such as vanilla javascript... using document.querySelector() and checking value property.
UPDATE
Many basic check could be made using simple procedural approach, if you want apply a minlength to the userinput1 field, on each onSubmit you need to check $scope.fields.userinput1.length > ..., et cetera...
A more clean and suggested way is to use html5 validation attributes,
angular decorates them and recognize thei rules, so, you can use min/max/min-length/max-length/required/pattern/disabled etc.
if you want to provide a reusable way, you should have a look at FormController.$addControl or how build a custom directive via attributes that requires ngModelController and so on...
Add required to those fields on which you want to add validation -
'use strict';
var app = angular.module("demo", [], function($httpProvider) {
});
app.controller("demoCtrl", function($scope) {
$scope.onSubmit = function(){
alert('form valid');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demo">
<div ng-controller="demoCtrl">
<form name="form" id="form" class="form-horizontal text-center" role="form" >
<input ng-required="true" ng-model="userinput1" name="userinput1" id="userinput1" class="" /><br>
Check it to make userinput 2 required: <input type="checkbox" ng-model="check" />
<input ng-required="check" ng-model="userinput2" name="userinput2" id="userinput2" class="" />
<br><input ng-click="onSubmit(DTOstep1)" ng-disabled="form.$invalid" name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" /><br>
</form>
</div>
</body>
you can also use ng-model inside ng-required to toggle the ng-required true and false.
angular automatically adds classed to each ng-model
This should help
https://docs.angularjs.org/guide/forms
Adding a fiddle as an example
https://jsfiddle.net/x0f6czfk/
<body ng-app="app">
<form ng-controller="mainCtrl">
<input ng-model="name" type="text">
<input ng-model="email" type="text">
<input type="button" ng-click="validateForm()" value="Save">
</form>
</body>
(function(window,document,undefined){
var app = angular.module('app',[]);
app.controller('mainCtrl',function($scope){
var self = this;
$scope.validateForm = function(){
//custom validation
if($scope.name === 'test'){
console.log('wrong name');
return;
}
//custom validation
if($scope.email === 'test#demo.com'){
console.log('wrong email');
return;
}
else{
//if no validation error, submit data;
console.log('valid form');
}
}
});
})(window,document)

form action change based on radio button selection in angular js

Now i have a form and two radio buttons.
Based on which radio button is selected I have to change my forms action.
here is the code
<form action={{action}} name="payform" method="post">
<div class="form-group">
<div class="radio radio-text">
<label>
<input type="radio" ng-model="cash" ng-click="paymethod('cash')" name="payment" value="cash">Cash
</label>
</div>
</div>
</div>
<div class="col-sm-12 col-md-4 col-lg-4">
<div class="form-group">
<div class="radio radio-text">
<label>
<input type="radio" ng-model="online" ng-click="paymethod('online')" name="payment" value="online">Online
</label>
</div>
</div>
<button class="btn btn-success" name="submit" type="submit">Submit</button>
</form>
And here is the controller code
$scope.paymethod = function(ptype){
alert("hi");
if(ptype=="cash"){
$scope.action = "food.php";
}
else if(ptype=="online"){
$scope.action = "online.php";
}
}
I used alert in the function to check if the function is being called or not. And alert is working it means function is being called but when i click submit nothing happens.
Not exactly what you asked for, but it solves your problem:
Prepend your form fields ng-models with formData.
Add ng-submit to your form
Use that function to place an $http request
Very basic example:
HTML:
<form name="payform" ng-submit="submitForm()">
<input ng-model="formData.value1" />
<input ng-model="formData.value2" />
<button type="submit"></submit>
</form>
JS:
$scope.submitForm = function submitForm() {
$http.post($scope.ptype + '.php', $scope.formData).then(
function success(response) {
// do something
},
function error(response) {
// not good
}
};
Because of prefixing your form ng-model attributes with formData, you have all fields contained in one object, which you can easily use when placing a POST request.

Change form's onsubmit function

I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>

How to stop form from resetting on submit

I have a simple form that triggers an ajax call but as soon as the submit button is clicked the form resets and clears all entries. Do you know how to prevent this? I'd like to have control over when the form gets cleared.The code is below. I suspect I need to abandon the submit function and detect the "click" event on a button.
JQuery
$("#Formid").submit(function(){loadAjax();});
HTML
<form id="Formid" method="put">
Name<BR/>
<input type="text" name="name"/><BR/><BR/>
Node Id<BR/>
<input type="text" name="node_id"/><BR/><BR/>
Type<BR/>
<input type="text" name="type"/><BR/><BR/>
Parent<BR/>
<input type="text" name="parent_id"/><BR/><BR/>
Longitude<BR/>
<input type="text" name="longitude"/><BR/><BR/>
Latitude<BR/>
<input type="text" name="latitude"/><BR/><BR/>
Description<BR/>
<textarea name="description" rows="5" cols="40">Insert description here</textarea><BR/><BR/>
<input type="submit" value="Add Node"/>
</form>
You can use preventDefault method of the event object.
$("#Formid").submit(function(event){
loadAjax();
event.preventDefault()
})
Alternatively, you could use event.returnValue = false;
$("#Formid").submit( function(e) {
loadAjax();
e.returnValue = false;
});
This works similarly to "return false;", except it will not exit the function.
You can use e.preventDefault() or return false; within a jQuery event handler:
$("#Formid").submit(function (e) {
loadAjax();
e.preventDefault(); // or return false;
});
e.preventDefault() will prevent the default event from occuring,
e.stopPropagation() will prevent the event from bubbling up and return
false will do both.
I have prevented form clearing for search form for my website mrnams.com
View
#using (#Html.BeginForm("Search", "Home", FormMethod.Post, new { #class = "navbar-form navbar-right pull-right" }))
{
<div class="input-group">
<input id="input-searchQuery" type="text" class="form-control" placeholder="Search this site" name="q">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
}
jQuery functions in View
#section scripts{
<script type="text/javascript">
$(function () {
var queryReturned = '#ViewBag.SearchQuery';
$("#input-searchQuery").val(queryReturned);
});
</script>
}
And here is the controller.
public class Home : Controller
{
public ActionResult Search(string q)
{
ViewBag.SearchQuery = q;
}
}
For demo visit https://mrnams.com/

Categories