Take a variable from thymeleaf th:each - java

Can i use variable charity from th:each in another block of code. For example
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}"></option>
</select>
<div>
<p th:text="${'You selected '+ charity.name}">
<div>

No, Thymeleaf is rendered on the server-side, so to accomplish this, you would need to use js or jQuery. Something like the code below should do the trick.
jQuery
$(document).ready(function() {
// If you want the option's text.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).find('option:selected').text()));
})
// If you want the option's value.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).val()));
})
})
UPDATE
If you would like to add more information from your charity object to your options, you could use th:attr. So, for example, if you want the charity's description and image name, then you could do something like the following.
HTML
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}" th:attr="data-description=${charity.description}, data-image=${charity.image}"></option>
</select>
Then, you could just get each attribute value using jQuery .attr() function.
$(document).ready(function() {
$('.select-field').on('change', function() {
var selectedOption = $(this).find('option:selected');
var name = $(selectedOption).text();
var id = $(selectedOption).val();
var description = $(selectedOption).attr('data-description');
var imageName = $(selectedOption).attr('data-image');
// Find your image by id.
var image = $('#myImage');
// Set your new image.
$(image).attr('src','/img/'+ imageName));
})
})

In HTML, you can make following change to div tag:
<div class="display-class">
<p></p>
<div>
This will help identify particular div
Then you can use jQuery to display the name of the selected option.
<script type="text/javascript">
$('.select-field').on("change", function() {
var selectedOption = $(this).find('option:selected').text();
$div = $('.display-class');
$p = $div.find('p');
$p.text("You selected: " + selectedOption);
});
</script>

Related

ajax call loader url loads same div tag multiple time issue

Could you please help me in sorting this issue as im just learning ajax and trying to incorporate for my requirement.
My Requirement:
When i click a particular image it should call the same page but load with the table data with different values based on the param values called.So I was advised to go for AJAX as it doesnt reload the whole page .
JQUERY
$("#goToCostTypeID").click(function () {
var costType = document.getElementById("costType").value;
if(costType == "Actual"){
costType = "Budget";
document.getElementById("costType").value = "Budget";
} //if actuals ends
if(costType == "Budget"){
costType = "Forecast";
document.getElementById("costType").value = "Forecast";
} //if actuals ends
if(costType == "Forecast"){
costType = "Actual";
document.getElementById("costType").value = "Actual";
} //if actuals ends
var Budget = costType;
$.ajax({
dataType : "html",
url:'my.jsp?productID=6&appID=6&txtHidden=Costs&mode=Edit&costType='+costType,
type:'POST',
contentType :'application/x-www-form-urlencoded; charset=UTF-8',
data:{costType:Budget},
success:function(result){
console.log("YES");
$("#costContent").load('my.jsp?productID=6&appID=6&txtHidden=Costs&mode=Edit&costType='+costType);
}
});
});
HTML
<td width="2%" id="goToCostTypeID"> <a href="#" ><img src="../images/goto.png"/></a></td>
<div id="costContent">
<td width="13%" ><input type="hidden" id="cost_type_<%=i+1 %>" name="cost_type_<%=i+1 %>[]" value="<%=Bean.getLevelTwoOrgId()%>"/><%=Bean.getCcLevel2()%></td>
<td width="12%" ><input type="hidden" id="intival_<%=i+1 %>" name="intival_<%=i+1 %>[]" value="<%=Bean.getInitProj()%>"/><%=Bean.getInitProj()%></td>
JAVA
String costType = request.getParameter("costType");
uploadCostList =DAO.doGetAppCostUploadedList(PK_AppID,costType,iPresentYear);
Im getting the same table multiple time when I click the image. Please help me.
With Regards,
Saranya C
As far as I can understand your requirements you need simply to do smth like this:
$("#goToCostTypeID").on('click', function() {
const currentCostType = $('#cost_type').val();
const nextCostType = currentCostType === 'Actual' ? 'Budget' : currentCostType === 'Budget' ? 'Forecast' : 'Actual';
$('#cost_type').val(nextCostType)
const url = 'my.jsp?' + $.param({
productID: '68',
appID: '68',
txtHidden: 'Costs',
mode: 'Edit',
costType: $("#costType").val()
});
$("#costContent").load(url);
});

How to get selected dropdown value in scriptlet

<select name="userSelected">
<option value="-1">---Select---</option>
<c:forEach items="${users}" var="user" varStatus="status">
<option value="${user.userId}">${user.userName}</option>
</c:forEach>
</select>
<button type="button" onclick="window.location.href='${pageContext.request.contextPath}/viewExpense/userSelected/<%=-1%>'">view</button>
when a user selects any value from dropdown then we can get the corresponging value using the name attribute (in this case name is "userSelected"). But how I can append this value in the href url above using that scriptlet. Someone help!!!
If you are linking to an anchor on a page you need to put a # in front of the anchor.
Try This
$("#yourDropdown").change(function () {
var selectedValue = $('#yourDropdown option:selected').val();
$("a").attr('href','#'+selectedValue); // just Append # tag before value
});
You can try something like :
<select id="userSelected">
----------
----------
</select>
<button type="button" onclick="submitPage();">view</button>
<script type="text/javascript">
function submitPage() {
var elm = document.getElementById("userSelected");
var strVal = elm.options[elm.selectedIndex].value;
window.location.href = '/viewExpense/userSelected/' + strVal;
}
</script>
If possible, you try the same thing using JQuery.
<select id="userSelected">
--------
--------
</select>
<button id="submitButton">view</button>
<script type="text/javascript">
$(document).ready(function() {
$('#submitButton').on('click', function() {
window.location.href = '/viewExpense/userSelected/' + $('#userSelected :selected').text();;
});
});
</script>

How to remove options from map on selection jsp?

<form:select id="name1"
<form:options items="${questionsMap}"/>
</form:select>
<form:select id="name2"
<form:options items="${questionsMap}"/>
</form:select>
<form:select id="name3"
<form:options items="${questionsMap}"/>
</form:select>
The questions map come from enum.Can anyone please help how can I remove the question from the questionsMap after it is selected on the first select and display the unselected ones the second time.
You can not do it on a JSP, as the code there will run on the server side - if you don't want do extra queries to the server... So the best way is to do it with JavaScript. Jquery selectors make this task easy.
Suggestion: http://api.jquery.com/remove/
Also, events that might interest you:
http://api.jquery.com/change/
There you can even find a as example...
Just to put my example here:
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$( this ).remove();
});
})
Instead of removing options from the drop-down you could simply validate the same options selected and show the error message on submit.
var validateSubmit = function() {
var errors = [];//trace all errors here
//fetch selected values from the drop-down starting name attribute with `name`
var txt = $('select[name^=name]').map(function() {
return this.value; //get current drop-down selected value
}).get(); //get all value in array
$.each(txt, function(i, v) {//loop in the selected values
if (i !== $.inArray(v, txt)) {//inArray, gives -1 if not found else array index
errors.push('Cannot select [' + v + '] more than once');
}
});
var submit = 0 === errors.length//true if no errors, else false
if (!submit) {
alert(errors.join('\n'));//concat all errors with \n
}
return submit;//submit if true, else don't submit
};
$(function() {
$('#form1').on('submit', validateSubmit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id='form1'>
<select name='name1'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name2'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name3'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<button>Submit</button>
</form>
OR
You could simply validate the same options selected and show the error message on change.
var names;
var validateChange = function() {
var errors = []; //trace all errors here
//fetch selected values from the drop-down starting name attribute with `name`
var txt = names.map(function() {
return this.value; //get current drop-down selected value
}).get(); //get all value in array
$.each(txt, function(i, v) { //loop in the selected values
if ('' !== v && i !== $.inArray(v, txt)) { //inArray, gives -1 if not found else array index
errors.push('Cannot select [' + v + '] more than once');
}
});
if (errors.length) {
alert(errors.join('\n')); //concat all errors with \n
}
};
$(function() {
names = $('select[name^=name]');
names.on('change', validateChange);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name='name1'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name2'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name3'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
This is a jquery code I made which does exactly this. Also leaves empty values in (if you have "Please select" in the top) and reinserts unselected values. It does it for all select elements on the page, if you need to restrict replace the selector $("select") with a more specific one:
$( document ).ready(function() {
manageSelectValues();
$("select").change(manageSelectValues);
});
function manageSelectValues()
{
$("select").each(function() {
var id = $(this).attr('id');
var value = $(this).find(":selected").val();
if (value) {
$("select[id!='" + id + "']").find("option").filter(function() { return this.value == value;}).remove();
}
$(this).find("option").filter(function() { return this.value != value;}).each(function() {
var unselValue = $(this).val();
$("select").filter(function() { return $(this).find("option").filter(function() { return this.value == unselValue;}).length == 0; }).append(
$('<option></option>').val(unselValue).html(unselValue));
})
});
}

Getting value from <select> in jsp

In my Java class I've declared an attribute like this,
String option = "<select name='logopt'><option value='fulllog'>Complete Log</option><option value='InfoLog'>INFO Log</option><option value='ErrorLog'>Error Log</option></select><br><br>";
request.setAttribute("LogOption", option);
in my jsp I've accessed the same like this,
<div id="box">${LogOption}</div>
Now as this is a select box, I want to get the select box value in Javascript How do I do this?
Like this -
JavaScript --> var selectVal = document.getElementsByName('logopt')[0].value;
jQuery --> var selectVal = $('select[name=logopt]').val();
Demo ----> http://jsfiddle.net/8t6mP/
Based on this answer
In my Java class I've changed what I had to,
String option = "<select name='logopt'onchange='xyz(this)'><option value='fulllog'>Complete Log</option><option value='InfoLog'>INFO Log</option><option value='ErrorLog'>Error Log</option></select><br><br>";
request.setAttribute("LogOption", option);
in my jsp page, I've added
function xyz(sel)
{
var val = sel.value;
alert(val);
}
and now this gives me the value of select
you can use attribute selector as specified of jquery as specified by Adil
<div>
<select name='logopt'>
<option value='fulllog'>Complete Log</option>
<option value='InfoLog'>INFO Log</option>
<option value='ErrorLog'>Error Log</option>
</select>
</div>
<input type="button" onClick ="return test();"/>
and js method
function test()
{
var x = $('select[name=logopt]').val();
alert(x);
}
jsfiddle link
jsfiddle

Dynamically adding duplicate (unique ID) form Div elements using javascript

I have a form having fields like:
<div class="row">
<div class="field">
<input class="" type="text" name="college" id="college"/>
</div>
<div class="field">
<input class="" type="text" name="city" id="city"/>
</div>
<div class="field">
<input class="" type="text" name="zip" id="zip"/>
</div>
</div>
<input type="button" class="buttonWidth" id="btnAddressAdd" value="Add Worksite Addressess"/>
I have a Add extra address button that add's another copy of div "row" to the page. I need to send all data from the page as a request to the Controller. How do I write a script that add's extra div copy onclick of the button and also appends a unique id to each of the new fields?
See working example in Dojo: http://jsfiddle.net/phusick/PeQCN/
And the same code in plain vanilla JavaScript: http://jsfiddle.net/phusick/Rceua/
The Dojo version employs dojo/_base/lang::clone as #Peter Rader mentioned:
// var lang = require("dojo/_base/lang");
// var array = require("dojo/_base/array");
// var query = require("dojo/query");
// var domAttr = require("dojo/dom-attr");
var counter = 0;
function duplicate(/*Node*/sourceNode, /*Array*/attributesToBump) {
counter++;
var out = lang.clone(sourceNode);
if (domAttr.has(out, "id")) { out.id = bump(out.id); }
query("*", out).forEach(function(node) {
array.forEach(attributesToBump, function(attribute) {
if (domAttr.has(node, attribute)) {
domAttr.set(node, attribute, bump(domAttr.get(node, attribute)));
}
})
});
function bump(/*String*/str) {
return str + "_" + counter;
}
return out;
}
How to use the aforementioned duplicate function:
// var dom = require("dojo/dom");
// var domConstruct = require("dojo/dom-construct");
var sourceNode = dom.byId("fieldset");
var node = duplicate(sourceNode, ["id", "name", "placeholder"]);
domConstruct.place(node, sourceNode, "after");
I have written code to achieve this.
Logic:
1) get the innerHTML of desired parent
2) replace id in the text
3) Insert the new html
See a working code
Pardon me for bad style of coding on JS part. I am not use to coding directly on DOM. I prefer JQuery.
Try
to use this snipplet (see usage)
http://dojotoolkit.org/reference-guide/1.8/dojo/_base/lang.html#dojo-base-lang-clone

Categories