how to set focus for elements in a spring based application - forms

I have a spring application where i validate all validations in custom spring validator class.
My form has nearly 15 fields.If there is a error in the last field , how to set the focus to that element.
Does spring tags support that. Any technical ideas ? Currently i display my error messages near the fields itself.

It is possible to use spring:bind tag to determine whether a field or the whole model object has error and the overall status of the object after processing (submission).
<spring:bind path="user.username">
<input id="inputId" type="text" name="${status.expression}" value="${status.value}"/>
<c:if test="${status.error}">
<c:forEach items="${status.errorMessages}" var"error">
<span class="field-error">${error}</span>
</c:forEach>
<script type="text/javascript">
document.getElementById('inputId').focus();
</script>
</c:if>
</spring:bind>
Note:
The status variable is exposed by the spring:bind tag.
The javascript part will focus the element when the specific field
has validation errors.

You can set autofocus to all fields that have an error, but your browser will only autofocus (and scroll) to the first one.
<spring:bind path="someFieldName">
<input type="text" name="someFieldName" value="${status.value}" ${status.error?'autofocus="autofocus"':''} />
</spring:bind>
You can't use spring's <form:input /> here as it doesn't work with conditional attributes.

I've used this:
<spring:bind path="*">
<c:if test="${status.error}">
<script type="text/javascript">
window.onload = function(){
document.getElementById('${status.errors.fieldErrors[0].field}').focus();
};
</script>
</c:if>
</spring:bind>
If there is an error it will find the first fieldError and its id and set the focus on that element
forgot to say that the beauty is that you don't need to put this code next to every input. One time is enough per jsp

Related

Input Group prepend - Bootstrap - can a reset button be included on the side of the input?

I have an input with a prepend from Bootstrap, looks nice and modifiable. I know I can put another button on the other side, but can that button be a reset? I have tried multiple things. Here is what I know and I will attach pictures below.
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Your calculation</span>
</div>
<input type="number" onkeypress="return isNumberKey(event)" onkeyup="return truncateDecimals(this, 2)" id="userInputMapOne" class="form-control" min="0" max="1000" step="0.01" aria-label="input value for your zone" value="e.g 12.34">
This is the current code I am using, it is NOT wrapped in a form. When I wrap it in a form things stop working for a strange reason. I am already having troubles with this, the min/max and step don't work (I have controlled min/max and step with JavaScript). So, is there a way to prepend (or append at the same time as a prepend) a second button onto that input and without being in a form and use that to clear the input field back to the default of ""?
It seemed like an easy job but this constantly interfered with the data being input. And for a weird reason, I can't seem to put a form just wrapping this input without upsetting the divs.
Note: While this would certainly work I think it would be in your bests
interests to review why a <form> is interfering with the
functionality of your code.
You cannot add a true <button type="reset">...</button> because you are not using a <form> and so the reset button doesn't know what to actually 'do'. You can quickly do something similar with just a few modifications of your existing code:
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Your calculation</span>
</div>
<input type="number" id="calculation" onkeypress="return isNumberKey(event)" onkeyup="return truncateDecimals(this, 2)" id="userInputMapOne" class="form-control" min="0" max="1000" step="0.01" aria-label="input value for your zone" value="e.g 12.34">
<div class="input-group-append">
<button role="button" class="btn btn-secondary" onclick="document.getElementById('calculation').value = ''">Reset</button>
</div>
</div>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
First you need to add an ID to your input field so that you can easily target the field with a bit of JavaScript. Then you just need to add an .input-group-append to extend the input-group to include the new button we'll be adding.
The button operates just like any button would, with the exception that there is an onclick event:
document.getElementById('calculation').value = ''
This finds the field with an ID value of calculation and on a click event resets the value of that field to empty. It's not a reset in the true sense of how <button type="reset">...</button> would operate, but functionally it achieves the same result.

Validating form with unpoly

I' trying to validate a form with unpoly. Here my HTML:
<div>
<label for="salesrepresentative-name">Name: </label><br/>
<input id="salesrepresentative-name" name="name" up-validate=".name-errors"/>
<span class="name-errors"></span>
</div>
And the error message what i get is:
Could not find failure target in response (tried [".name-errors", "body"])
Any ideas, what i'm doing wrong?
up-validate will submit the form and replace your current <span class="name-errors"> with the same span from the response.
The error message you received means that the form submission did not include a <span class="name-errors">. If even did not include a <body> tag (which Unpoly uses as a fallback when selectors are missing).
Try to submit the form without Unpoly and see if the response is what you're expecting.

Input field with validation crashes when typing fast in Angular 2

I have a form in Angular 2 with a simple validation using Validators.
The html template
<form role="form" #myForm="ngForm" (ngSubmit)="submit()" novalidate [ngFormModel]="form">
<div class="form-group list-element">
<label for="name">name*</label>
<input type="text" name="name" class="form-control" ngControl="name"
#name="ngForm" placeholder="Enter name" [(ngModel)]=user.name >
</div>
</form>
The ControlGroup for the validation
ngOnInit() {
this.form = new ControlGroup({
name: new Control('', Validators.compose([
Validators.required,
Validators.pattern("(([a-zA-Z ]|[0-9])+)*"),
Validators.minLength(5),
Validators.maxLength(80)
]))
});
}
When I type fast (random) characters in the input field (e.g #1KZBZKBjkndedjk###kjbzdzdékj!) the application crashes. This does not happen always so I have not really noticed a pattern.
This is the place where the crash happens, so I think the crash has something to do with the pattern.
That's a known issue https://github.com/angular/angular/issues/7822 and will probably be fixed when this pull request lands https://github.com/angular/angular/pull/7421
First of all this is not related to AngularJS.
This happens because your pattern is wrong I don't know what pattern you need but for example if you need to validate email then use this pattern
& Just Check for your pattern nothing else.
your code....
Validators.pattern("^[_a-z0-9]+(.[_a-z0-9]+)#[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,4})$"),
your code ends...
That it!

Getting error while submitting form data using post method in AEM / CQ

There is a cq page and in the page there are many component. In one component we have HTML form code. After submitting form data ,i need to set all value in PageContext and use these value in other component on same page.
To achieve this I have created component named "MySamplecomponent". and in put all html code as below.Also i have created a POST.jsp under same component.
Mysamplecompnent.jsp code
<%#include file="/libs/foundation/global.jsp"%>
<%
//String collapsed = properties.get("selection","");
String collapsed= request.getParameter("testKey");
out.println("value++"+collapsed);
String category= request.getParameter("skill");
out.println("Category++"+category);
pageContext.setAttribute("collapsed1",collapsed,PageContext.REQUEST_SCOPE);
%>
<form name="form1" id="form1" action="${currentPage.path}.html" method="post">
<input type ="text" name="testKey" id="testKey" value="collapsed" />
<input type ="hidden" name="pathValue" id="pathValue" value="myValue" />
<select name="skill" style="display:block">
<option value="1">Cricket</option>
<option value="2">Volley ball</option>
<option value="3">Tennis</option>
</select>
<input type="radio" name="ravi" id="radiobutton" value="success" > radiobutton<br>
<input id="SubmitButton" name="SubmitButton" type="submit" value="SubmitButton" onclick="javascript:location.href='#'" />
</form>
After clicking on submit button getting below error
Error while processing /content/myPage/
Status
500
Message
javax.jcr.nodetype.ConstraintViolationException: No matching property definition: testKey = collapsed
Location /content/myPage/
Parent Location /content
Path
/content/myPage/
Referer http://localhost:4502/content/myPage.html
ChangeLog
Go Back
Modified Resource
Parent of Modified Resource
First of all, I believe you mean PageContent under PageContext. If you want to use Sling Post Servlet, you need to change the action.
${currentPage.path} refers to Page node and not PageContent node. Page node has pretty strict restrictions for properties and you can not put there any custom props, like testKey. So to make your code work just replace your action attribute with ${currentPage.path}/jcr:content and it will work.
Use JQuery and AJAX. See this article:
http://scottsdigitalcommunity.blogspot.ca/2013/06/posting-form-data-to-adobe-cq-using.html

Questions about grails form

Assuming that i have the following data in my params
params:[input:[1, 2, 3]]
And i have the following form in my Grails app
<div class="block1">
<label class="control-label">
<g:message code="input.label" default="Input"/>
</label>
<div class="controls">
<g:textField id="input1" name="input" value="${input}" readonly="${actionName != 'show' ? false : true}"/>
</div>
</div>
<div class="block2">
<label class="control-label">
<g:message code="input.label" default="Input"/>
</label>
<div class="controls">
<g:textField id="input2" name="input" value="${input}" readonly="${actionName != 'show' ? false : true}"/>
</div>
</div>
<div class="block3">
<label class="control-label">
<g:message code="input.label" default="Input"/>
</label>
<div class="controls">
<g:textField id="input3" name="input" value="${input}" readonly="${actionName != 'show' ? false : true}"/>
</div>
</div>
The form design above is correct, because in my form design, there will be several inputs of the same name (but each will be saved to the database under different primary keys) and it can be increases and decreases according to user selection.
Few questions using the above
How do i make it so that the value for input1 is params.input[0], input2 is params.input[1] and input3 is params.input[2] in the view? I can pass the model from controller without problem, but i couldn't distribute the value properly to each input on the form.
Is there any way to change the value ${input} dynamically? As in if i want to change the value to ${input[0]} or ${input[1]}
Can i automatically set the amount of block appended into the form using the g:each tag? Say like if from controller i want to set the rendering block amount to 3, so can i use the g:each tag to render the block 3 times in the form?
Thanks
The links are examples of how to use ajax/jquery to get values from a remote call and replace html element (divId) within a page - this divId could be the entire
<input type="text" name="input" value="newvalue"/>
upon triggering some form of call as above to get the new value.. in regards to
g:textField
yes it works like all other grails tags in the end they are transformed back to the correct HTML terminology...
The actual variable value is dynamic if you defined
<input name="existingvariable" value="${something}" ...
where something was a parameter from the given controller - and then you updated the call so
://YOURHOST:8080/yourapp/controller?existingvariable=newvalue
and refreshed or clicked this link which is what ajax would be doing for you doing a new call to either another controller to generate new values or same and passing new value to it and then grabbing data and pushing it back onto the divId ... (all in the background)
Groovy loading into divs
Grails - Select menu not rendering
I want my selects dropdowns to auto populate with Ajax in Grails website
The above are all related to using ajax to populate / update existing form elements
If you wish to update a live form with a new live value (non existant in DB) take a look at modaldynamix plugin. //github.com/vahidhedayati/modaldynamix