Spring MVC: Populate a dropdown based on another - spring

this enum is define in one of my class
public enum Type {
TEXT(1), BINARY(2);
private final int type;
AttributeType(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
Dropdown menu #1
<label class="col-sm-3 col-md-3 col-lg-3 control-label"
style="font-weight: bold; font-size: 12px; color: #666666">
<span style="color: red;">*</span> Type
</label>
<div class="col-sm-9 col-md-9 col-lg-9">
<form:select class="form-control"
style="width: 80%" path="">
<form:option value="" selected="true" disabled="true"
label="Select a type" />
<c:forEach var="attribute" items="${Type}">
<form:option value="${attribute}" />
</c:forEach>
</form:select>
<form:label class="error" id="errorStatus" path=""
style="color: red;">${errorStatus}</form:label>
</div>
Dropdown menu #2
<label class="col-sm-3 col-md-3 col-lg-3 control-label"
style="font-weight: bold; font-size: 12px; color: #666666">
<span style="color: red;">*</span> Constraint
</label>
<div class="col-sm-9 col-md-9 col-lg-9">
<form:select class="form-control" style="width: 80%" path="">
<form:option value="" selected="true" disabled="true"
label="Select a Constrait" />
<c:forEach var="type" items="${Type}">
<c:if test="{type== TEXT}">
<form:option value="" label="test1" />
</c:if>
<c:if test="{type== BINARY}">
<form:option value="" label="test2" />
</c:if>
</c:forEach>
</form:select>
<form:label class="error" id="errorConstraint" path=""
style="color: red;">${errorStatus}</form:label>
</div>
In my Controller class, I have add the list to my attribute model.addAttribute("TypeValue", Arrays.asList(Type.values()));
What I am trying to do:
Drop down menu #2 to display test1 if user have selected TEXT in Drop down menu #1 and
display test2 if user selected BINARY in Drop down menu #1
Actual result
Nothing is being display after selecting either options in drop down menu #1

using jquery
var diction = {
TEXT: ["B1", "B2", "B3"],
BINARY: ["B4", "B5", "B6"]
}
// bind change event handler
$('#EventId').change(function() {
// get the second dropdown
$('#SecondDropdown').html(
// get array by the selected value
diction[this.value]
// iterate and generate options
.map(function(v) {
// generate options with the array element
return $('<option/>', {
value: v,
text: v
})
})
)
// trigger change event to generate second select tag initially
}).change()
and I remove all the <c:if test> tag. This solution is base on this post.
I am open to ways to improve my code too

Related

Spring mvc include one single 'form' for different c:url

I am working on a spring-mvc application. In the application, there are various types of events, for which the user can register. As for registration, there is a standard formula with details like firstName, email, address, etc. I am just giving different c:url values depending which event it is.
I was wondering if it is possible to include the form(not the c:url part) in another jsp file, and just call jsp:include. This would serve me very well as when the form needs to be styled, updated, etc, then I need to update only one file. I am including how the form looks. Kindly have a look. Thank
eventregistration.jsp :
<c:url var="addAction" value="/student/add/seminar-e-commerce" ></c:url>
<form:form class="seminar-form" action="${addAction}" commandName="students">
<table>
<form:hidden path="studentid"/>
<label>Firstname/LastName <span class="color-red">*</span></label>
<form:input path="firstname" type="text" class="span6 border-radius-none" />
<span> </span>
<form:input path="lastname" type="text" class="span6 border-radius-none pull-right" />
<label>Email-Address <span class="color-red">*</span></label>
<form:input path="emailadress" type="text" class="span12 border-radius-none" />
<label>Street Name/Number <span class="color-red">*</span></label>
<form:input path="address1" type="text" class="span10 border-radius-none" />
<span> </span>
<form:input path="address2" type="text" class="span2 border-radius-none pull-right" />
<label>City/PLZ <span class="color-red">*</span></label>
<form:input path="city" type="text" class="span10 border-radius-none" />
<span> </span>
<form:input path="plz" type="text" value="" class="span2 border-radius-none pull-right" />
<label>Handy Number <span class="color-red"></span></label>
<form:input path="handynumber" type="text" value="" class="span12 border-radius-none" />
<label path="newsletterpermission">Want to subscribe newsletter?</label>
<form:radiobutton path="newsletterpermission" class="form-control" value="true"/>Yes
<form:radiobutton style="margin-left:15px" path="newsletterpermission" class="form-control" value="false"/>No
<br/>
<br/>
<c:if test="${empty students.firstname}">
<input class="btn-u" type="submit"
value="<spring:message text="Register for event"/>" />
</c:if>
</table>
</form:form>
Any pointers would be nice. Thanks a lot.
You can achieve this with an entrypoint/method in your controller with a Pathvarible of action like below
#RequestMapping(value="/student/{action}", method = RequestMethod.POST)
public String EntryPoint(#PathVaribale String action, ModelMap model) {
switch (action) {
case "add":
// delegate to addMethod
break;
case "activate":
// delegate to activateMethod
break;
case "register":
// delegate to registerMethod
break;
default:
///Unsurported operation
}
return "index";
}
and you can keep the c:url , remember to set up the model.action attribute on a controller method responsible for setting up the form bean, for your case students bean or make it more general
<c:url var="action" value="/student/model.action/" ></c:url>

Bootstrap: Validation states with form-inline fields?

Is there any way to use Bootstrap's form field validation states/classes (warning, error, info, success) on form-inline fields (without using control-group)?
I'm using Bootstrap, and I have a large form that uses the form-horizontal class for layout. However, there are areas within the form where the fields need to be inline (for example, City/State/Zip). I'm using form-inline for this, which works fine. Here's the basic markup:
<form id="account-form" class="form-horizontal" method="post" action="" novalidate>
<!-- Address -->
<div class="control-group">
<label class="control-label">Address</label>
<div class="controls">
<input type="text" name="address" />
</div>
</div>
<!-- City, State, Zip -->
<div class="control-group">
<label class="control-label">City</label>
<div class="controls form-inline">
<input type="text" name="city" />
<label>State</label>
<input type="text" name="state" />
<label>Zip Code</label>
<input type="text" name="zipcode" />
</div>
</div>
</form>
In my particular situation I need to handle validation manually. Unfortunately, it seems Bootstrap's validation state classes must be applied to the control-group; as you can see in the example above, the control-group in my case contains multiple fields. I tried wrapping individual fields within control-group spans or divs, but control-group does not play nicely at all when used with both a form-inline and form-horizontal together!
Is there a CSS class or other rule I can attach to a field directly (or an otherwise-innocent field wrapper) to apply these styles to individual fields, without having to completely redeclare all the standard bootstrap styles??
You could create some custom less code and recompile bootstrap:
Add #import "_custom.less"; to less/bootstrap.less
create less/_custom.less:
// Mixin for inline form field states
.inlineformFieldState(#warning: success,#textColor: #555, #borderColor: #ccc, #backgroundColor: #f5f5f5) {
// Set the text color
label.#{warning},
.help-block .#{warning},
.help-inline .#{warning}{
color: #textColor;
}
// Style inputs accordingly
.checkbox .#{warning},
.radio .#{warning},
input.#{warning},
select.#{warning},
textarea.#{warning} {
color: #textColor;
}
input.#{warning},
select.#{warning},
textarea.#{warning} {
border-color: #borderColor;
.box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work
&:focus {
border-color: darken(#borderColor, 10%);
#shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(#borderColor, 20%);
.box-shadow(#shadow);
}
}
// Give a small background color for input-prepend/-append
.input-prepend .add-on .#{warning},
.input-append .add-on .#{warning} {
color: #textColor;
background-color: #backgroundColor;
border-color: #textColor;
}
}
.form-inline{
.inlineformFieldState(success, #successText, #successText, #successBackground);
.inlineformFieldState(warning, #warningText, #warningText, #warningBackground);
.inlineformFieldState(info, #infoText, #infoText, #infoBackground);
.inlineformFieldState(error, #errorText, #errorText, #errorBackground);
}
This mixin is based on .formFieldState in less/mixins.less. After recompile bootstrap you could use (see also: http://jsfiddle.net/bassjobsen/K3RE3/):
<form>
<div class="container">
<div class="control-group">
<div class="controls form-inline">
<label class="error">City</label>
<input class="error" type="text" name="city" />
<label class="warning">State</label>
<input class="warning" type="text" name="state" />
<label class="success">Zip Code</label>
<input class="success" type="text" name="zipcode" />
<label class="info">Street</label>
<input class="info" type="text" name="street" />
</div>
</div>
</div>
</form>
I do this, remove control-group from div container and use form-group instead, but put this in each input div, I do not secure that works with control-group.
This url maybe can help you http://formvalidation.io/examples/complex-form/, this not work for me ^_^!.I hope help you.
<div class="row">
<div class="col-lg-12">
<div class="col-lg-4 form-group" >
<select class="form-control" name="pais">
<option value="" selected disabled>Pais</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
<div class="col-lg-4 form-group" >
<select class="form-control" name="estado">
<option value="" selected disabled>Estado</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="">C</option>
</select>
</div>
<div class="col-lg-4 form-group">
<select class="form-control" name="ciudad">
<option value="" selected disabled>Ciudad</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
</div>
</div>
something like this will work.
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
//******** added custom code.
$('input[type="radio"]').closest('.col-sm-9').find('.invalid-feedback').hide();
$('input[type="radio"]:invalid').closest('.col-sm-9').find('.invalid-feedback').show();
}, false);
//******** added custom code.
});
}, false);
})();
</script>
code above is almost of document, added custom code at the end of submit event listener.
#read
https://getbootstrap.com/docs/4.0/components/forms/#validation

How can I Add Custom Validation in Kendo Grid Popup

How can I add validation for minimum length to a Textbox and display custom error messages?
I want validation for the following:
UserName to have a minimum length of 6
Password and Confirm Password to match
Address1 is required
Here is the code for the popup template. The specified minlength in the template is not working but the maxlength is working properly.
<script id="popup_editor" type="text/x-kendo-template">
<table cellpadding="0" cellspacing="0">
<tr>
<td>
<label for="UserName"><b>UserName*</b></label>
</td>
<td>
<div class="control-row">
<input type="text"
name="UserName"
id="UserName"
class="k-input k-textbox"
required
**minLength**="6"
maxlength="8"
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter username"/>
<span class="k-invalid-msg" data-for="UserName" ></span>
</div>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<div>
<label for="Password"><b>Password*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="password"
id="Password"
name="Password"
class="k-input k-textbox"required
validationMessage="Please enter Password"/>
<span class="k-invalid-msg" data-for="Password"></span>
</div>
</td>
<td>
<div>
<label for="ConfirmPassword" style=""><b>Confirm Password</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="password"
id="ConfirmPassword"
name="ConfirmPassword"
class="k-input k-textbox"required
validationMessage="Please enter Confirm Password"/>
</div>
</td>
</tr>
<tr>
<td>
<div>
<label for="Company_Name"><b>Company Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input name="Company_Name"
id="Company_Name"
required
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter Valid CompanyName"/>
</div>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<div>
<label for="First_Name"><b>First Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="text"
name="First_Name"
id="First_Name"
data-type="string"
data-bind="value:First_Name"
class="k-input k-textbox" required
pattern="[a-zA-Z]+"
validationMessage="Please enter FirstName"/>
</div>
</td>
<td>
<div>
<label for="Last_Name"><b>Last Name*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<input type="text"
id="Last_Name"
name="Last_Name"
class="k-input k-textbox" required
pattern="[a-zA-Z]+"
validationMessage="Please enter LastName"/>
</div>
</td>
</tr>
<tr>
<td>
<div>
<label for="Address1"><b>Address1*</b></label>
</div>
</td>
<td>
<div class="k-edit-label">
<textArea style="resize: none;"
rows="5"
cols="18"
name="Address1"
maxlength="150"
id="Address1" required
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter Address">
</textarea>
</div>
</td>
</tr>
</table>
You can add custom validation for popup editing within the dataSource of your grid.
var dataSource = new kendo.data.DataSource({
transport: {
...
},
schema: {
model: {
id: "UserName",
fields: {
UserName: {}
Password: {}
ConfirmPassword: {}
Company_Name: {}
First_Name: {}
Last_Name: {}
Address1: {
validation: {
minLength: function (input) {
if (input.is("[name=UserName]")) {
return input.val().length >= 6;
}
return true;
},
match: function (input) {
if (input.is("[name=ConfirmPassword]")) {
return input.val() == $("#Password").val();
}
return true;
}
}
}
}
}
}
});
There are a few things to respect:
The validation runs for ALL input elements within your popup, therefore
you only have to define it for ONE of the fields in your model. Which one does not matter.
you have to check which input element is checked in the current run, which does the if statement in my example.
you have to append a return true at the end of each and every rule you define or otherwise you'll get an error message for every input you're not explicitly checking. If there's no return value passed, kendo automatically assumes the check had a false result.
Every validation rule needs its own validation message or otherwise your validation tooltip box will only display a warning logo without any text. You can add it as an html attribute (data-{validation rule}-msg) in your input elements, like this:
<input type="text"
name="UserName"
id="UserName"
class="k-input k-textbox"
required
maxlength="8"
pattern="[a-zA-Z0-9]+"
validationMessage="Please enter username"
data-minLenght-msg="Username must be at least 6 characters"/>
<input type="password"
id="ConfirmPassword"
name="ConfirmPassword"
class="k-input k-textbox"
required
validationMessage="Please enter Confirm Password"
data-match-msg="Password and confirmation must be equal"/>
Hope this helps
In rules add this:
match: function (input) {
if ((input.is('[name=\'Password\']') || input.is('[name=\'ConfirmPassword\']'))&& $('#ConfirmPassword').length !== 0) {
if ($('#Password').val().length > 0 && $('#ConfirmPassword').val().length > 0) {
if (input.is('[name=\'Password\']')) {
return input.val() === $('#ConfirmPassword').val();
}
else if (input.is('[name=\'ConfirmPassword\']')) {
return input.val() === $('#Password').val();
}
}
}
return true;
},
minLength: function (input) {
if (input.is("[name=UserName]")) {
return input.val().length >= 6;
}
return true;
},
requiredAddress: function (input) {
if (input.is("[name=Address1]")) {
return $('#Address1').val() !== '' ? false : true;
}
return true;
}

How to add an increment value for each id attribute within the div contents with cloned jQuery object

Having a hard time figuring out how to add an increment value for each id attribute within the div contents with cloned jQuery object.
http://jsfiddle.net/hvK8d/
===================== HTML=====================
<div class="upload-file-container">
<div class="uploadFile left clearfix">
<input type="file" id="FileUpload1">
<table id="RadioButtonList1">
<tbody>
<tr>
<td><input type="radio" value="Resume" id="RadioButtonList1_1">
<label for="RadioButtonList1_1">Resume</label></td>
<td><input type="radio" value="Letter of Recommendation" id="RadioButtonList1_2">
<label for="RadioButtonList1_2">Letter of Recommendation</label></td>
<td><input type="radio" value="Other" id="RadioButtonList1_3">
<label for="RadioButtonList1_3">Other</label></td>
</tr>
</tbody>
</table>
</div>
Remove </div>
<div class=""><a class="plus" href="javascript:;">plus one</a></div>
===================== JQUERY =====================
//Cloning upload file control
$('.remove').live('click', function () {
if (confirm("Are you sure you wish to remove this item?")) {
$(this).parent().slideUp('fast', function () {
$(this).remove();
});
}
return false;
});
$('.plus').click(function () {
console.log('cloning');
var divCloned = $('.upload-file-container:first').clone();
divCloned.hide().insertAfter('.upload-file-container:last').slideDown('fast');
return false;
});
For the sake of completeness I will put here a small solution making use of a "template."
A class for hiding the template:
.upload-file-container.template {
display: none;
} ​
A small function to do replacements:
$.fn.template = function(variables) {
return this.each(function() {
this.innerHTML = this.innerHTML.replace(/{{(.+)}}/g, function(match, variable) {
return variables[variable];
});
return this;
});
};
A template:
<div class="upload-file-container template">
<div class="uploadFile left clearfix">
<input type="file" id="FileUpload{{id}}">
<table id="RadioButtonList{{id}}"><tbody>
<tr>
<td>
<input type="radio" value="Resume" id="RadioButtonList{{id}}_1">
<label for="RadioButtonList{{id}}_1">Resume</label>
</td>
</tr>
</tbody></table>
</div>
</div>
Usage:
var count = 0;
var divCloned = $(".upload-file-container.template")
.clone()
.removeClass("template")
.template({
id: count++
});
Instead of using numbered IDs, you should be using the array-like notation (e.g. RadioButtonList[]) in the name attribute, and wrap your labels around the inputs:
<td>
<label for="RadioButtonList1_1">
<input type="radio" value="Resume" name="RadioButtonList1[]">
Resume
</label>
</td>
<td>
<label for="RadioButtonList1_2">
<input type="radio" value="Letter of Recommendation" name="RadioButtonList2[]">
Letter of Recommendation
</label>
</td>
<td>
<label for="RadioButtonList1_3">
<input type="radio" value="Other" name="RadioButtonList3[]">
Other
</label>
</td>
P.S. You should also consider using a more descriptive name than RadioButtonList.

Build dynamic checkboxes

Hey guys I have about 8 fieldSets and Im iterating over a list. I want to fill up the checkboxes based off a value of each iteration for ex.
<c:if test="${detBean.groupName == 'HEADER_DATA}">
*Add that checkbox to that fieldset and so on...
<c:forEach var="detBean" items="${detFields}">
Display Name -- ${detBean.displayName}
Field Name -- ${detBean.fieldName}
Group Name -- ${detBean.groupName}
</c:forEach>
<tr>
<td>
<div id="displayFields" style="display:block;">
<fieldset class="det">
<legend>Header Data</legend>
<input type="checkbox" name="${detBean.displayName}
" value="${detBean.displayName}
">${detBean.displayName}
</input>
</fieldset>
<fieldset class="det">
<legend>Materiel Data</legend>
<input type="checkbox" name="${detBean.displayName}
" value="${detBean.displayName}
">${detBean.displayName}
</input>
<br/>
</fieldset>
</td>
</tr>
Thankx
This worked:
<div id="displayFields" style="display:block;">
<fieldset class="det">
<legend>Header Data</legend>
<c:forEach var="detBean" items="${detFields}">
<c:if test="${detBean.groupName == 'HEADER_DATA'}">
<input type="checkbox" name="${detBean.displayName}" value="${detBean.displayName}">${detBean.displayName}</input>
<br/>
</c:if>
</c:forEach>
</fieldset>
<fieldset class="det">
<legend>Materiel Data</legend>
<c:forEach var="detBean" items="${detFields}">
<c:if test="${detBean.groupName == 'MATERIEL_DATA'}">
<input type="checkbox" name="${detBean.displayName}" value="${detBean.displayName}">${detBean.displayName}</input>
<br/>
</c:if>
</c:forEach>
</fieldset>

Resources