AngularJs - submit the form programmatically - javascript

I read several answers on this topic but they don't seem to apply to my problem. My problem is quite complex. I have a form which uses ReportViewer.ASPX. The form is defined as following:
<form name="form" novalidate role="form"
sm-dirty-check
id="reportViewer"
method="post"
action="~/Infrastructure/ReportViewer/reportViewer.aspx"
target="viewerIFrame"
ng-show="crud.showForm" class="ng-cloak">
#* Form inputs *#
<input type="hidden" name="labelType" value="Rental" />
<input type="hidden" name="labelLayoutId" value="{{ crud.model.lbLayoutId }}" />
<input type="hidden" name="itemsToPrint" value="{{ crud.jsItemsToPrint }}" />
The actual forms are defined in the tabs using ng-form (I only shared the top portion of my Edit form which is relevant to my question).
I also have these buttons at the bottom of the form:
<button type="submit"
ng-if="crud.model.lbLayoutId!==0"
name="generateLabelButton"
id="generateLabelButton"
class="btn btn-primary pull-left"
ng-click="crud.generateLabel()"
ng-disabled="crud.isSaveButtonDisabled">
#Labels.generateLabel
</button>
<div class="pull-left generateLabelButton">
<data-desc:type ng-if="crud.model.lbLayoutId===0"
value="#Labels.generateLabel"
keep-pristine="true"
on-after-selection="crud.layoutSelected(selectedValue)"
title="{{ '#string.Format(Labels.selectX, Labels.labelLayout)'}}"
param="layouts"
message="#string.Format(Labels.selectX, Labels.labelLayout)"
selected="crud.model.lbLayoutId"
descrip-value="descrip"
id="layoutPickerButton"
name="layoutPickerButton"
button-type="button"
type="7"
filter-by="Label"
description="crud.model.lbLayout">
</data-desc:type>
</div>
So, if I have lblLayoutId defined, I have my regular submit button and I press it and get my form submitted and all is well.
If I don't have the lblLayoutId defined (it's 0), I need to use a directive which has a template for a button, when I press it, it opens a modal form to pick the layout, etc.
So, my problem is that after I picked the layout, I need to submit my form so the label can appear.
I tried making the directive to be of type submit (button-type property), this didn't work.
I also tried the following code in the method which is executed by the button when value is selected:
rentalEquipmentsCrudController.prototype.layoutSelected = function (selectedValue) {
this.model.lbLayoutId = selectedValue;
$("#generateLabelButton").click();
}
rentalEquipmentsCrudController.prototype.generateLabel = function () {
if (this.model.lbLayoutId === 0) return;
this.jsItemsToPrint = "";
this.itemsToPrint = this.getItemsToPrint();
this.jsItemsToPrint = JSON.stringify(this.itemsToPrint);
angular.element($("#viewerIFrame").contents()
.find("#reportViewer_ReportViewer")).empty();
let actionPath = angular.element($("#reportViewer")).attr("action");
if (actionPath.slice(-3) !== "pdf") actionPath += "/Labels.pdf";
angular.element($("#reportViewer")).attr("action", actionPath);
this.showViewer = true;
};
The layoutSelected method is executed from my directive and the next code is executed by my regular button.
So, I'm at lost as how to make it work.

The role of forms in client-side AngularJS applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload. Instead post JSON data and receive JSON data responses. Go to the server for data, but not html/js/css etc.
Read AngularJS <form> Directive API Reference - Submitting a form and preventing the default action.

You don't want to combine ng-click with a button of type="submit", this will still cause the form to submit (non-programmatically). Instead, use type="button". Alternatively, you can keep type="submit" but add the ng-submit="crud.generateLabel()" to the form element
<form>
...
<button type="button" ng-click="crud.generateLabel()">...</button>
</form>
Alternatively:
<form ng-submit="crud.generateLabel()">
...
<button type="submit">...</button>
</form>

Related

Alfresco submit form

When i validate the form on alfresco with the submit button, the process return with the previous url.
I would submit my form and then go to one url i have on javascript.
If you cant help thank you.
i have try this without success :
< input onclick="window.location.href = 'http://test.test.test';" type="submit" value="Submit request" />
and this one doesn t work too :
< button type="button" value="submit" onclick="redirect to url test">
The submission-url allows the action attribute of the generated form to be overridden so that the contents of the form can be submitted to any arbitrary URL. You will require a custom form template(ftl) and js along with your form if you want any additional customization with the OOTB forms processing.
<#if form.mode != "view">
<form id="${formId}" method="${form.method}" accept-charset="utf-8" enctype="${form.enctype}" action="${form.submissionUrl}">
</#if>
Please refer the below link for additional information.
https://docs.alfresco.com/4.2/tasks/forms-custom-formtemplate.html

javascript call before submit using thymeleaf does not work as expected

I am new to javascript so it might be a simple question for many.
I have used form sumbit in thymeleaf and am trying to add a JS validation before the form is submitted to the spring mvc controller. I can perform these two actions separately (individual tasks). However I could not really make them work one after the other (js function and form submit). Submit action is triggered by a button inside the form.
<form th:action="#{/user/trigger}" th:object="${triggers}" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="submit" id="ignore" name="action" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
The js function is like below:
$(".ignore").click(function() {
//do some processing;
return false;
});
So can someone can help me to rewrite this code which will first call the JS function and submit the form to the java spring mvc controller? Thanks in advance.
The issue with your approach is that after your java-script is validating the code, your html 'submit' button is submitting the form as they're executing one after another. You haven't done anything to prevent the form submission after the validation is getting failed.
To overcome this issue, what you can do is to submit the form through your JavaScript code manually only when your validation is successful.
So your code will look something like this -
1.) Changes in Html code, instead of creating the button type as 'submit', make it as a normal button and run your javascript validation function on its click -
<form th:action="#{/user/trigger}" th:object="${triggers}" id="myForm" method="post">
<input type="hidden" name="tradeDate" th:value="${trigger.id.tradeDate}">
<button type="button" id="ignore" name="action" onclick="myValidationFunction()" value="ignoreOrder" class="btn btn-primary btn-sm">Ignore</button>
</form>
2.) Changes in Javascript code, now after clicking on the above button your javascript validation function will execute and after the validation is successful submit the form manually using the form id, something like this -
function myValidationFunction(){
if( some_condition ){
//validation failed
return;
}
//validation success , when above mentioned if condition is false.
$("#myForm").submit(); // Submit the form
}
For more information about using submit in jquery, refer the official documentation -
https://api.jquery.com/submit/
for jquery, it return a list, so:
$('#search_form')[0].submit();

Programmatically submit a form from an Angular directive

In my Angular 1.5.X app I have a directive with the following template
<form id="pdfDownloadForm"
name='pdfDownloadForm'
method="POST"
action="{{ downloadUrl }}">
<input type="hidden" name="data" value="" />
<button type="button" ng-click="submit()">Submit</button>
</form>
When the form is submitted, I would like to do the following
Set the value of the hidden parameter data to a value retrieved from a remote service
Submit the form
Attempted Solution
Presumably the easiest way to set the hidden parameter is with
<input type="hidden" name="data" ng-model="dataValue" />
and then before submitting the form, assign to scope.dataValue the value retrieved from the remote service?
I tried to submit the form programmatically with
scope.submit = function () {
$('#pdfDownloadForm').submit();
}
But this causes the following error:
Error: [$rootScope:inprog] $apply already in progress
Since you're using Angular 1.5+, there's no reason to use scope - either use controllerAs syntax or, preferably, components.
I'd implement your task by interrupting first submit call and populating hidden field instead. Any subsequent submits are allowed to happen.
// inside contorller
onSubmit(event) {
if (!this.dataValue) {
event.preventDefault();
this.initializeData();
}
}
initializeData() {
$http.get('/my-data-source').then((response) => {
this.dataValue = response.data.value;
this.pdfDownloadForm.submit(); // requires <form name="$ctrl.pdfDownloadForm">
});
}
See https://docs.angularjs.org/api/ng/directive/ngSubmit
It's better to avoid using ngClick here since form can be submitted by Enter instead of button click.
<button type="button" ng-click="submit">Submit</button>
should be
<button type="button" ng-click="submit()">Submit</button>
so after your edit to your post, this wasn't the solution? have your tried it?

Multiple form submit with one Submit button

I have two forms. I want to submit both forms with 1 button. Is there any method that can help me do it?
Example:
<form method="post" action="">
<input type="text" name="something">
</form>
<form method="post" action="">
<input type="text" name="something">
<input type="submit" value="submit" name="submit">
</form>
I want both forms to be submitted with 1 submit button. Any help would be appreciated.
The problem here is that when you submit a form, the current page is stopped. Any activity on the page is stopped. So, as soon as you click "submit" for a form or use JavaScript to submit the form, the page is history. You cannot continue to submit another page.
A simplistic solution is to keep the current page active by having the form's submission load in a new window or tab. When that happens, the current page remains active. So, you can easily have two forms, each opening in a window. This is done with the target attribute. Use something unique for each one:
<form action='' method='post' target='_blank1'>
The target is the window or tab to use. There shouldn't be one named "_blank1", so it will open in a new window. Now, you can use JavaScript to submit both forms. To do so, you need to give each a unique ID:
<form id='myform1' action='' method='post' target='_blank1'>
That is one form. The other needs another ID. You can make a submit button of type button (not submit) that fires off JavaScript on click:
<submit type='button' onclick="document.getElementById('myform1').submit();document.getElementById('myform2').submit();" value='Click to Submit Both Forms'>
When you click the button, JavaScript submits both forms. The results open in new windows. A bit annoying, but it does what you specifically asked for. I wouldn't do that at all. There are two better solutions.
The easiest is to make one form, not two:
<form action='' method='post'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='submit' value='Submit'>
</form>
You can place a lot of HTML between the form tags, so the input boxes don't need to be close together on the page.
The second, harder, solution is to use Ajax. The example is certainly more complicated than you are prepared to handle. So, I suggest simply using one form instead of two.
Note: After I submitted this, Nicholas D submitted an Ajax solution. If you simply cannot use one form, use his Ajax solution.
You have to do something like that :
button :
<div id="button1">
<button>My click text</button>
</div>
js
<script>
$('#button1').click(function(){
form1 = $('#idIFirstForm');
form2 = $('#idISecondForm');
$.ajax({
type: "POST",
url: form1.attr('action'),
data: form1.serialize(),
success: function( response ) {
console.log( response );
}
});
$.ajax({
type: "POST",
url: form2.attr('action'),
data: form2.serialize(),
success: function( response2 ) {
console.log( response2 );
}
});
});
</script>
You could create a pseudo form in the background. No time to write the code, jsut the theory. After clicking submit just stop propagation of all other events and gather all the informations you need into one other form you append to document (newly created via jquery) then you can submit the third form where all the necesary infos are.
Without getting into why you want to use only 1 button for 2 forms being submitted at the same time, these tools that will get the input data available for use elsewhere:
Option 1...
Instead of using <form> - collect the data with the usual Input syntax.
ex: <input type="text" name="dcity" placeholder="City" />
Instead of using the form as in this example:
<form class="contact" method="post" action="cheque.php" name="pp" id="pp">
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button class="button" type="submit" id="submit">Do It Now</button>
</form>
use:
<label for="invoice">Your Name</label>
<input type="text" id="invoice" name="invoice" />
<button type="button" onclick="CmpProc();" style="border:none;"><img src="yourimage.png"/> Do It Now</button>
Then code the function CmpProc() to handle the processing/submittion.
Inside that function use the Javascript form object with the submit() method as in...
<script type="text/javascript">
function submitform() {
document.xxxyourformname.submit();
}
</script>
Somehow I suspect making the two forms into one for the POST / GET is worth reconsidering.
Option 2...
Instead of POST to use the data to the next page consider using PHP's $_SESSION to store each of your entries for use across your multiple pages. (Remember to use the session_start(); at the start of each page you are storing or retrieving the variables from so the Global aspect is available on the page) Also less work.
Look man. This is not possible with only HTML. weither you gether the inputs in one form or else you use jquery to handle this for you.

How to handle multiple submit buttons in a form using Angular JS?

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form and then reset it - allowing them to enter another entry.
How do I accomplish this in angular? I was thinking I could have two submit buttons with ng-click tags, but I'm using ng-submit on the form element. Is there any reason I NEED to be using ng-submit - I can't remember why I started using that instead of ng-click on the button.
The code looks something like:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button type="submit">Save and Add Another</button>
</form>
</div>
And in the controller SomeController
$scope.record = {};
$scope.save = function (record) {
$http.post('/api/save', record).
success(function(data) {
// take action based off which submit button pressed
});
}
You can keep both ng-click and type="submit". In the ng-click you can just update a parameter of your controller and validate that in the event ng-submit:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button type="submit" ng-click="SaveAndAddClick=true">Save and Add Another</button>
</form>
So this approach avoids you from adding a method and then calling a redundant code.
Thanks
ngSubmit allows you to press Enter while typing on the textbox to submit. If that behavior isn't important, just use 2 ngClick. If it is important, you can modify the second button to use ngClick. So your code becomes:
<div ng-controller="SomeController">
<form ng-submit="save(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit">Save</button>
<button ng-click="saveAndAdd(record)">Save and Add Another</button>
</form>
</div>
Make them all buttons and type=submit. It makes it a little cleaner not mixing and matching inputs and buttons. So basically you're trying to execute one method in your controller to handle either button click.
<div ng-controller="SomeController as sc">
<form ng-submit="sc.execute(record)">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit" ng-model="sc.saveButtonVal" ng-click="sc.saveButtonVal=true>Save</button>
<button type="submit" ng-model="sc.saveAndAddButtonVal" ng-click="sc.saveAndAddButtonVal=true">Save and Add Another</button>
</form>
</div>
So, in your js file you'll have something like this.
function SomeController() {
var sc = this;
sc.execute = function(record) {
//initialize the vars
sc.saveButtonVal = false;
sc.saveAndAddButtonVal = false;
sc.resetButtonValues = function() {
sc.saveButtonVal = false;
sc.saveAndAddButtonVal = false;
};
if (sc.saveButtonVale) {
//do save only operation
} else if (sc.saveAndAddButtonVal) {
//do save and add op
}
// reset your button vals
sc.resetButtonValues();
}
}
As I see it, you have two options:
1: Use an ngClick event on the "save and add another" button and remove the "type='submit'" portion. Then in whatever function you call gor the ngClick, you can save and then reset the values, calling save() within that function.
2: Remove the ngSubmit altogether and just use ngClicks for both buttons.
If someone looking for a simple approach then just create a flag and toggle between button and submit.
<button type="{{isButton == true ? 'button' : 'submit'}}" >Save</button>
<button type="{{!isButton == true ? 'button' : 'submit'}}" >Update</button>
Need to handle the flag according to user action.
ng-submit has other advantages too. For example, invalid form will not be submitted. It is always better to use ng-submit instead of ng-click. However, in your scenario, better approach would be
use ng-click on buttons.
validate form in controller. Keep in mind that ng-click will submit the form even if it is not valid.
call two different $scope.functions on two different ng-click in the somecontroller.
Hope it helps.
Remove ng-submit from "form" element and define ng-click functions separately on each button with type 'submit'.For invalidation check, define name property in form element tag. And check validation in scope function.
<div ng-controller="SomeController">
<form name="saveForm">
<input type="text" name="shoppingListItem" ng-model="record.shoppingListItem">
<button type="submit" ng-click="save(record)">Save</button>
<button type="submit" ng-click="saveOther(record)">Save and Add Another</button>
</form>
Scope Function:
$scope.record = {};
$scope.save = function (record) {
if(this.saveForm.$valid)
{
$http.post('/api/save', record).
success(function(data) {
// take action based off which submit button pressed
});
}
}

Categories

Resources