I want to submit a form in angularjs which are like survey, suppose
user will fill the form and submit, I have array of all the questions
of form, I want to update all the questions with the respected answers
by iterating all the questions from array and update each question
individually(why because I only have API to update one question)
This is my form
<ng-form name="participateSurveyForm" novalidate>
<div class="form_fields_survey_audience" ng-repeat="questionlistitem in surveyquestiondata">
<h3 class="">{{questionlistitem.question}}</h3>
<div ng-show="questionlistitem.question_type == 'multiple_choice'">
<div class="radio" ng-repeat="optionofanswers in questionlistitem.options">
<div class="form-group">
<label>
<input type="radio" name="optionforanswer" ng-model="surveydataforparticipate.optionforanswer" ng-value="optionofanswers.option" required checked>{{optionofanswers.option}}
</label>
</div>
</div>
</div>
<div ng-show="questionlistitem.question_type == 'open_text'">
<div class="form-group" >
<textarea class="textAreaMultiligne" name="open_text_field" ng-model="surveydataforparticipate.open_text_field" required placeholder="Answer Here" rows="10" cols="40"></textarea>
</div>
</div>
</div> <!--End Row-->
<div class="row">
<div class="col-lg-12">
<button type="submit" ng-click="participateInSurvey(surveydataforparticipate)" class="btn btn-primary">Complete</button>
</div>
</div><!--row & Submit Button-->
</ng-form>
//Anguar Code
$scope.participateInSurvey = function(surveydataforparticipate){
angular.foreach(surveydataforparticipate, function(value){
$http.put('/api/survey/question/+value._id, surveydataforparticipate).success(function(data){
console.log(data);
});
});
}
not getting values from this surveydataforparticipate function. also
Is it correct that i have put foreach to submit the data using $http?
Thanks for helping.
You can define a function in your controller where the form should go on submit. And, use ng-submit to link that function to your form.
<ng-form name="participateSurveyForm" ng-submit="submitForm ()" novalidate>
In your controller :
$scope.submitForm = function(){
//definition of the function.
//access form data here.
}
Related
I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.
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.
I have a register form that I wish to do validation on the moment a user clicks submit. This is what the HTML looks like:
<form ng-submit="RegistrationC.fireReg()" novalidate name="register">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" autocomplete="off" class="form-control" placeholder="First Name" ng-model="RegistrationC.first_name" required name="first_name">
<div class="help-block" ng-messages="register.first_name.$error" ng-show="submitted && register.first_name.$error">
<p ng-message="required">This field is required.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group col-md-offset-3">
<button type="submit" class="btn btn-success btn-block" ng-click="submitted=true">Register Now</button>
</div>
</div>
</form>
It is showing the validation message if a username is not typed in, but it still submits. What am I missing?
EDIT 1
//init.js - RegistrationController
reg_list.fireReg = function () {
var url = 'user/register';
api.makeCall(reg_list, url)
.then(function (response) {
reg_list.response = response;
console.warn(response);
$location.path('/user/verify');
})
.catch(function (errorMessage) {
console.log("got an error in initial processing", errorMessage);
event.restoreButton();
});
};
I know there's issues in this function, I will fix them at a later stage.
Submit this form only if it is valid. <whatever_form_name>.$valid
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
Just add checkpoint whether form is valid or not before submitting form
Try like this
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">
If you want to disable html5(or browser) validator, You have to remove 'required' attribute in your html code
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.w3schools.com/tags/att_input_required.asp
I have an Angular page with a form for adding people, and a button (outside this form) to submit the list of people.
When the user focuses on a text input in the form, and then clicks to submit the list, the validation error from the text input appears but the submit event never occurs.
An example of this issue here: http://plnkr.co/edit/6Z0UUs
<div ng-controller="MyCtrl as vm">
<form name="form1" novalidate="">
<input type="text" name="field1" ng-model="vm.name" required>
<div ng-messages="form1.field1.$error" ng-if="form1.field1.$touched">
<label ng-message="required">Name is required</label>
</div>
<!--
This form adds a person to a list. I've not included this code to keep the example simple
<input type="submit" value="Add person">
-->
</form>
<button ng-click="vm.submit()">Submit list</button>
</div>
-
angular.module('myApp',[])
.controller('MyCtrl', function() {
var vm = this;
vm.name = '';
vm.submit = function () {
alert('submitted');
};
});
To replicate:
Click on the text input but leave blank
Click submit
Current behavior: "Name is required" appears thanks to the validation. Clicking 'Submit' again displays the 'submitted' alert.
Expected behavior: "Name is required" appears thanks to the validation and the 'submitted' alert appears.
Desired behavior: The 'submitted' alert appears and I add some code to vm.submit() to hide the 'Name is required' validation message as it's not important when the list is submitted.
I've observed that removing the ng-messages block fixes the issue, but I do need to show a validation message. Using a more basic directive (ng-show) to show the validation message instead does not help.
Any insights into what I'm doing wrong, or workarounds to achieve my desired behavior, would be great!
[Modified Answer] :
Here is a working plunker : http://plnkr.co/edit/JCyRi8xp4L3FtafABblS?p=preview
vm.preventDefaultIfSubmitted = function($event){
if($event.relatedTarget.id == "submit"){
$event.stopImmediatePropagation();
}
};
The idea is to get the $event when the blur occurs and then to look at the id of the relatedTarget (which is your button in this case) and if it is then you cancel the $event, otherwise you keep it.
That way if you click anywhere your validation message appears and if you click on submit it doesnt
May this help for form validation
<form role="form" name="projectBriefFrm">
<div class="form-group">
<label for="project_title">Project Title
<sup>*</sup>
</label>
<input ng-model="project.title" ng-required="true" type="text" class="form-control" name="title" placeholder="Untitled Project"
/>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.title.$invalid">Please provide title</span>
</div>
<div class="container" id="editor-title">
<label for="project_brief">Project Brief
<sup>*</sup>
</label>
<div class="row" id="editor">
<div class="col-lg-12 nopadding">
<textarea ng-model="project.brief" name="brief" cult-editor ng-required="true"></textarea>
</div>
</div>
</div>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.brief.$invalid">Please provide project brief</span>
</div>
</div>
</form>
I have the following form:
<form class="form-horizontal" {{action "formSubmit"}}>
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
As you notice, I have two actions for this form:
When I type on the user input field and press enter, it fires the findUser action
When the form submits, the formSubmit action is called.
Now, here's the problem.
When I type something on the user text field and press enter, it fires the findUser action but also fires the formSubmit. As I know, this is how a form normally behaves. When you press enter on a text field, it submits the form.
Is there a workaround on this behavior? That when I press enter on a the user text field, I want the findUser action to be fired but not submit the form.
Please help.
One workaround is removing form itself. You can have action on button. You may have to sacrifice some form related features but still works very well. Here is the jsbin.
http://emberjs.jsbin.com/nifim/2/edit
There might be some other better way as well.
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser" bubbles=false}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary" {{action "formSubmit"}}>Save</button>
and javascript
App.IndexController = Ember.Controller.extend({
actions: {
findUser: function(){
console.log('Find User');
},
formSubmit: function(){
console.log('Form Submit');
}
}
});
Another workaround that allows using the form:
http://emberjs.jsbin.com/povud/1/
Just add 'onkeypress="return event.keyCode != 13;"' to the form element and place the {{action}} on the button itself:
<form class="form-horizontal" onkeypress="return event.keyCode != 13;">
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button class="btn btn-primary" {{action "formSubmit"}}>Save</button>
</form>