How to scroll to error in form? - forms

I have just started using AngularJS, I would like to know this approach to scroll the page to the first input with an error when I submit a form.
Here is the way with jQuery :
$('html, body').animate({
scrollTop: $("--- #ID OF THE FIRST INPUT WITH ERROR ---").offset().top
}, 2000);
How to do this in Angular ?
HTML
<form class="form" novalidate>
<input type="text" class="nom-du-projet" ng-model="fields.nom" required />
<p ng-show="fields.nom.$invalid && !fields.nom.$pristine">The name is required.</p>
<input type="text" ng-model="fields.cible" />
...
<button type="submit" ng-click="submit(fields)">Add</button>
</form>
JS
$scope.submit = function(fields){
console.log(fields);
$http
.post('/xxxx', fields)
.success(function(response) {
// success
})
.error(function(response) {
// scroll to field error
});
}

You could use the $anchorScroll service.
$location.hash("<errorFieldID>");
$anchorScroll();
Or you could just use:
$window.scrollTo //you could even get bold and user window.scrollTo
There are a couple plugins out there that say they can do it.. but I unfortunately have not vetted them so I can't recommend any.

You could try something like this:
//scroll to an anchor by ID
$scope.scrollToAnchor = function (anchor) {
if (anchor !== null) {
$location.hash(anchor);
$anchorScroll(anchor);
}
}
//use above function
$scope.scrollToAnchor($scope.myForm.$error.required[0].$name);
//or any ID
$scope.scrollToAnchor('ID');

I have a written a angularJS directive for the same purpose, you can include the directive as bower component and use this functionality without having to write any extra code for any form in your application. Please do let me know, if any improvements or corrections/enhancements are needed for the directive.
https://github.com/udayvarala/ng-scroll-to-error
Thanks,

Related

Why Is my script freezing up when I hit enter?

The majority of the Add-on is good but whenever I hit enter (which is, in my opinion, the most common way to submit a form, for example, a login form), but all it does is blank out.
I've tried linking the script with a onkeydown like so:
<div onkeydown="handle(event)">blagh blagh blagh</div>
but I still get the same results:
<html>
<form id='myForm' style="font-family:Georgia;">
<table>
<tr><td><h2>Enter your Password</h2></td></tr>
<tr><td><p>DO NOT HIT ENTER ON YOUR KEYBOARD!!!!!</p></td></tr>
<tr><td><input name='password' type='password' value="" onkeypress="handle(event)"></td></tr>
<tr><td><div id="submitbuttcontainer"><img id="submitloader" style="display:none;" src='https://lh6.googleusercontent.com/-S87nMBe6KWE/TuB9dR48F0I/AAAAAAAAByQ/0Z96LirzDqg/s27/load.gif' /><input id="submitbutt" type='button' onclick='showWorking();google.script.run.withSuccessHandler(onSuccess).decodeForRequest(document.getElementById("myForm"));' name="Submit" value="Submit"></div></td></tr>
</table>
</form>
<script>
function onSuccess(obj) {
document.getElementById('submitbutt').style.display="block";
document.getElementById('submitloader').style.display="none";
if(obj.status == 'success') {
google.script.host.closeDialog();
browser.msgbox('Access Granted', browser.buttons.OK)
}
else {
browser.msgbox('ALERT!!','!OOF!','Incorrect Password. Please retry', browser.buttons.OK);
}
}
function showWorking() {
document.getElementById('submitbutt').style.display="none";
document.getElementById('submitloader').style.display="block";
}
function handle(e){
if(e.keyCode === 13)
document.getElementById('submitbuttcontainer').click();
}
</script>
</html>
All I'm trying to do is get the form to submit when I hit enter and not blank out. I always hit enter to submit a form but in this case all it does is blank out the form and all I have is whiteness.
Here's the link for the complete source code (don't know if this will work because I'm in a school district):
https://script.google.com/a/bcsdschools.net/d/1_YUx4ZP3qEWVcFMc-MvfEYX2S34r7-b4M0iRlE_JQa81T3ZubN5OeISa/edit)
Problem
Hitting enter key results in form submission (which is explicitly forbidden in Apps Script due to its client-to-server communication implementation).
Solution 1 - handle inputs individually
Add preventDefault() to a keydown event if key is enter (btw, keypress event is deprecated, see reference on MDN, use the keydown / keyup instead):
var ENTER_CODE = 13;
function handle(e) {
if(e.keyCode === ENTER_CODE) {
e.preventDefault();
document.getElementById('submitbuttcontainer').click();
}
}
Solution 2 - handle form submit
You can listen for a submit event on your form instead and invoke preventDefault() as the only statement in event handler or handle form submission at the same time if you expect form to be submitted on enter key hit:
//assumption: form is initiated elsewhere in code;
form.addEventListener('submit', (event) => {
event.preventDefault();
//handle submission;
});
You can also prevent all forms from being submitted to make the setup flexible:
(() => {
const { forms } = document;
Object.values(forms).forEach(
form => form.addEventListener("submit", (e) => e.preventDefault())
);
})();
Or, alternatively, use event delegation and register one listener on the document since the event bubbles up:
document.addEventListener("submit", (e) => e.preventDefault());
Suggestion
Please, use addEventListener instead of on[event name here] attributes. This way is much more flexible and has the benefit of being concise and easy for others to read.
References
Handling forms in Apps Script guide
Why use addEventListener? MDN reference
I wanted to try to give you a complete answer, but I have to admit that I may know less about event handlers than you. But this seems to work for me.
aq4.html:
<html>
<head>
<script>
window.onload=function() {
preventFormSubmit1();
}
function preventFormSubmit1() {
console.log('preventFormSubmit1');
var form=document.forms['myForm'];
form.addEventListener('submit',function(e) {
e.preventDefault();
});
}
function handleFormSubmit(formObject) {
console.log('handleFormSubmit');
var first=document.forms['myForm']['first'].value;
var last=document.forms['myForm']['last'].value
var sheet=document.forms['myForm']['sheet'].value;
console.log('%s,%s,%s',first,last,sheet);
if(first.length>0 && last.length>0 && sheet.length>0) {
google.script.run
.withSuccessHandler(function(msg){
var div=document.getElementById('output');
div.innerHTML=msg;
var inputs=document.querySelectorAll('input[type=text]');
inputs[0].focus();
for(var i=0;i<inputs.length;i++) {
inputs[i].value='';
}
})
.processForm(formObject);
}else{
alert("Invalid or Incomplete Data");
}
}
console.log("MyCode");
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input type="text" name="first" /> First<br />
<input type="text" name="last" /> Last<br />
<select name="sheet">
<option value="Sheet1">Sheet1</option>
<option value="Sheet2">Sheet2</option>
</select> Sheet<br />
<input id="sub" type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
aq1.gs:
function processForm(formObject) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(formObject.sheet);
sh.appendRow([formObject.first,formObject.last]);
return Utilities.formatString('First: %s<br />Last: %s<br />Sheet: %s', formObject.first,formObject.last,formObject.sheet);
}
function runOne() {//This loads the dialog
var userInterface=HtmlService.createHtmlOutputFromFile('aq4').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Form Example")
}

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});

Submit selection on Bootstrap typeahead() autocomplete?

How do I autosubmit the selection made with Twitter Bootstrap typeahead()??
http://twitter.github.com/bootstrap/javascript.html#typeahead
There is a clean way using the updater callback:
input.typeahead({
'source' : ['foo', 'bar'],
'updater' : function(item) {
this.$element[0].value = item;
this.$element[0].form.submit();
return item;
}
});
When user selects an option (either by mouse click or keyboard), the callback populates the input box and sends the form.
If you use the external typeahead.js plugin (recommended for Bootstrap 3):
To trigger a form on select just use the custom events.
$('#my-input')
.typeahead({/* put you options here */})
.on('typeahead:selected', function(e){
e.target.form.submit();
});
More info on custom events here and demo about JSfiddle.
Might not be the best solution, but I just tried this on my typeahead setup locally and it worked.
If your typeahead looks something like this...
<form id="test-form" method="post" action="">
<input id="test-input" type="text" data-provide="typeahead"
data-source='["1","2',"3"]' />
</form>
Then you can submit it with this javascript.
<script type="text/javascript">
$('#test-input').change(function() {
$('#test-form').submit();
});
</script>
Apparently there are a few git merge requests. This one does the job and allows you to send an array of objects to typeahead: https://github.com/twitter/bootstrap/pull/1751
I added a blur callback on the input. Be aware that you need to wait for a short period, that typeahead can change the value in the input and the blur callback is not called before that. It's just a workaround, but it works.
$('input.myTypeaheadInput').blur(function(e) {
window.setTimeout(function() {
window.console && console.log('Works with clicking on li item and navigating with the keyboard. Yay!');
}, 50);
});
To populate a value of a hidden field in an html form from the typeahead data selection, I did the following:
$('#prefetch').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'trees',
source: trees,
limit: 15
}).on('typeahead:selected', function(e) {
var result = $('#prefetch').val()
$('#formpane input[name=\"myID\"]').val(result)
});
For reference, here's the html code:
<body>
<div id="formpane">
<form action="/thanks" method="POST">
<input class="typeahead" type="text" placeholder="select categories" id="prefetch">
<button type="submit">Submit</button>
<input type="hidden" name="myID" />
</form>
</div>
<script type="text/javascript" src="js_file_above.js"></script>
</body>

Submit the value of a <p> element when an html form is submitted

I have this code: <p class = "foo">Text</p>
And I also have a form: <form action = "XXX.php" method = post></form>
However, how can I get the value of the <p> when I submit it, as the <p> element can be changed.
So what I mean is to be able to post the value of the <p> when the user submits the form, and to be able to access it from that php file with: $_POST['foo'];
Thanks, I have tried to be as clear as possible.
You have to use Javascript for that
A jQuery function that will work
$("form").submit(function(){
var value = $("p").html();
// If foo already exists
if( $("[name=foo]").length > 0 )
{
$("[name=foo]").val(value);
}
else
{
var input = $("<input />", { name : "foo",
value : value ,
type : "hidden" });
$(this).append(input);
}
});
Use
<input type="hidden" value="something" name="something" id="something" />
and when you change inner html of <p> change the value of hidden input.
I think your best bet is to make it an input with readonly enabled, and style to to look like a <p>. It's better then trying to add it to the POST parameters with JavaScript.
Here's a quick example. I bet it could still be improved with a few extra CSS quirks, experiment a bit.
The easiest thing to do is set the value of a hidden form field when you change the contents of your <p>.
Alternatively, you can get its contents and post with JavaScript.
For text you need to use input field:
<input type="text"/>
Form fields should must have an id:
<input type="text" id="pewpew" class="foo"/>
I would go with:
<input type="text" id="pewpew" class="foo" value="default text goes here"/>
OR
Go with different workarounds, like setting form's hidden elements on the fly, etc.
You can create hidden field on the fly and set its value on form submit. Like this:
<form id="form" action="/somewhere" method="post">
<p>Some text</p>
<input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
var form = document.getElementById('form');
form.onsubmit = function()
{
var p = this.getElementsByTagName('p')[0];
if (!document.getElementById('pval'))
{
var pinput = document.createElement('input');
pinput.setAttribute('type', 'hidden');
pinput.setAttribute('id', 'pval');
pinput.setAttribute('name', 'p');
this.appendChild(pinput);
}
document.getElementById('pval').value = p.innerHTML;
return true;
}
</script>
Works, i've tested.

Load page to Modal Window from form with jQuery

I´m working on a website with a purchase process. I have a form generated by some PHP that looks like this:
<form name="order_form" action="'.$thePayreadApi->get_server_url().'" method="post" id="payer-form">
'.$thePayreadApi->generate_form().'
<input type="submit" value="Klicka för betalning" />
</form>';
When the form is submitted it will go to a new page (located on another server) where the purchase is performed.
Basically what I want is the form to be submitted through AJAX and then load the new page in a Modal Window. I use jQuery throughout the website so I´d like a solution based on that lib.
I´ve found these sites that might be a hint:
http://pixeline.be/blog/2008/javascript-loading-external-urls-in-jqmodal-jquery-plugin/
http://dev.iceburg.net/jquery/jqModal/
Any help is really appreciated!
I haven't tried this exactly, but the theory is what I would go for:
$("form[name='order_form']").submit(function() {
//Validate in here
var validate = false;
if($("input[form='element1']").val()!="") {
validate = true;
}
if(validate) {
this.submit();
} else {
return false;
}
});
<form action="shopping.php" target="targetIframe" method="post">
<input type="submit" value="Click Me" />
</form>
<iframe name="targetIframe" src=""></iframe>