i have little modified this question which already exist
<form ng-submit="add()">
<input type="text" name="field">
<input type="submit" value="Submit">
</form>
I'd like to have input[name="field"] value as a parameter of add().
Is there any way to do that?
Answer to question
Html:
<div ng-controller="MyFormController">
<form ng-submit="add(field)">
<input type="text" name="field" ng-model="field" />
<input type="submit" value="Submit" />
</form>
</div>
JS:
app.controller('MyFormController', ['$scope', function(scope) {
scope.add = function(field) { // <-- here is you value from the input
// ...
};
}]);
my problem is
HOW to reset input field to be empty after form submit in this case
Your HTML should be like that:
<div ng-controller="MyFormController">
<form ng-submit="add()">
<input type="text" name="field" ng-model="fieldname" />
<input type="submit" value="Submit" />
</form>
</div>
and your JS field should be like that:
app.controller("MyFormController", function($scope) {
$scope.add = function () {
var hi=$scope.fieldname;//you can use it parametre
}
});
After two days googling i found my solution with this statement
give an id to the input field for example 'clearfield' and than add the following
statement after the .success function
angular.element('#clearfield').val('');
You don't need to pass this as an argument. Since your input has a ng-model="field" this is a $scope variable which is accessible in your function already
app.controller('MyFormController', ['$scope', function(scope) {
$scope.add = function() {
// your code here
$scope.field = ''; // reset field to an empty string
};
}]);
Related
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)
I have a problem. When I use static template on render page
<form name="AddArticle" ng-submit="addArticle()" class="form add-article">
<input type="text" value="first" init-from-form ng-model="article.text[0]" />
<input type="text" value="second" init-from-form ng-model="article.text[1]" />
</form>
And when I do submit form, I get data:
{text : {0: "first", 1: "second"}}
But I have dynamic moment. By clicking I add dynamic input
$(".button").click(function(){
$('.form').append('<input ng-model="article.info" init-from-form type="text" />');
})
Ok. All appended, but by submit I still get data without dynamic input.
Tell me please, how to get all fields form???
Number one, don't mix jQuery like that when you can use angular. Try something like this:
view
<form name="AddArticle" ng-submit="addArticle()" class="form add-article">
<p ng-repeat="object in data track by $index">
<input type="text" ng-model="object.text" />
</p>
</form>
<button ng-click="addInput()">
add
</button>
{{data}}
</div>
controller
angular.module("app", [])
.controller("testCtrl", function($scope) {
$scope.data = [];
$scope.addInput = function() {
$scope.data.push({});
}
})
https://jsfiddle.net/pntd3kaf/
<form action="<c:url value = "/deal/#value-that-user-enters#"/>" method="POST">
Kindly enter the deal id : <input type="text" name="dealId">
<input type="submit" value="Get the deal" />
</form>
In the above code, I want the action attribute of form to be /deal/(deal-id-entered-by-user). Is there any way to do it without using any javascript? And is it at all possible even with javascript?
You should be able to do it simply with javascript like this:
document.querySelector('form').onsubmit = function() {
this.setAttribute('action', "/baseurl/" + document.querySelector('input[name=dealId]').value)
}
<form action="/baseurl/" method="POST">
Kindly enter the deal id :
<input type="text" name="dealId">
<input type="submit" value="Get the deal" />
</form>
The best way is to change the form action by javascript:
document.forms[0].action=documnet.getElementById('dealId').value;
You can use it like this:
<form action="<c:url value = "/deal/#value-that-user-enters#"/>" method="POST">
Kindly enter the deal id : <input type="text" class="myBox" name="dealId">
<input type="submit" value="Get the deal" />
</form>
$('.myBox').on('change', function (event) {
var myVal = $(this).val();
$('form').attr('action', function(i, value) {
return value + myVal;
});
});
I am creating form in angularjs. In that, I am creating add more fields functionality by clicking on "Add more" button. I've implemented add more functionality using javascript.
Below is the code for HTML:
<form method="POST" name="form" ng-submit="insert(user)" role="form">
<div class="top_gets" id="innerdivs">
<input ng-model="user.amount" type="text"/>
<input ng-model="user.description" type="text"/>
<input type="submit" onclick="addMore();" value="Add more"/>
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
Below is Javascript Code:
<script>
var counter = 0;
function addMore() {
counter += 1;
var div = document.getElementById('innerdivs');
var innerdiv = '<div id="innerdivs"><!-- Same Form Field Elements---></div>';
$('#innerdivs').append(innerdiv);
}
</script>
My problem is, whenever I add more fields by clicking on "Add more" button and submit the form, then only first loaded input fields posts/sends the data means newly appended field input does not posts the data. Whatever the fields are appended using javascritpt that won't works that is form does not sends/posts the inputs. This works with core PHP but it does not works in angularjs. Is there any way to fix this in angularjs?
You are doing it absolutely wrong. You shall not add dom elements manually. Instead, you shall have array in controller and push new object in it:
<form name="form" ng-submit="save(users)" role="form" ng-controller="addUserCtrl">
<div class="top_gets" ng-repeat="user in users">
<input ng-model="user.amount" type="text" />
<input ng-model="user.description" type="text"/>
<input type="button" ng-click="addMore();" value="Add more" />
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
In controller:
angular.module(<module_name>).controller('addUserCtrl', ['$scope', function (scope) {
scope.users = [{}];
scope.addMore = function () {
scope.users.push({});
};
scope.save = function () {
// send `scope.users` to server with $http or $resource
};
}]);
how can i get a specific element of a text input into a variable via javascript, in other words take the example below
<form id="123">
<input type="text" id="supply_qty" />
<input type="submit" name="submit" id="123" />
</form>
How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc... is that i later want to use ajax with it, but for the moment i just need the variable.
Thanks
The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now
Simple Example:
var button = document.getElementyById("123");
button.onclick = function() {
var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};
Using jQuery make a slight change to your markup. I am just going to add some classes.
<form>
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
then
$(".submit").click(function() {
var txtbox = $(this).parent("form").children(".textbox")[0];
});
Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.
<form class="tinyforms">
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
Then
$('.tinyforms').submit(function() {
var txtbox = $(this).children(".textbox")[0];
});
If you accept using jQuery you can do this:
DOM
<form class="form" action="false">
<input type="text" value="some input" name="textInput" />
<input type="text" value="some text" name="textInput2" />
<input type="submit" class="sumbit" value="Send" />
<div id="results"></div>
</form>
And JavaScript
$(".form").submit( function(){
var inputs = $(this).serializeArray();
$.each(inputs , function(i, input){
$("#results").append(input.value + "<br />");
});
return false;
} );
EDIT: Updated code and Fiddle: http://jsfiddle.net/65Xtp/4/