I have a JSP with a select input in a form, like so:
<form method="post" action="/confirm">
<select id="dropdown" name="dropdown">
<option value="1">1st choice</option>
<option value="2">2nd choice</option>
<option value="3">3rd choice</option>
</select>
<input type="submit" value="submit" name="submit" />
</form>
I have a spring controller that handles this form as follows:
#RequestMapping(value = "/confirm", method = RequestMethod.POST)
public ModelAndView confirm(#RequestParam int dropdown,
HttpServletRequest request,
Model model)
{
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("selection", dropdown);
modelAndView.setViewName("confirm");
return modelAndView;
}
On my confirm view, if I want to display the value of the dropdown selection then I can do that like this:
<div id="dropselection">${selection}</div>
If the user selected the first option, "1st choice", for example, then the value that would be passed to the confirm page would be 1.
However, what if I want to pass along the text value from the select tag option? What if a user selected the first option and I needed the value 1st choice to be passed into the controller? How would I retrieve that?
You can't retrieve that value. In form submission it only pass value attribute of select, input tags.
Two options available
You can change value field text to description
If you have hard code that just change that to
<option value="3rd choice">3rd choice</option>
If you have dynamic code, then you can use this kind of approach
List<Answer> answerList = new ArrayList<Answer>();
Answer answer = new Answer();
answer.setAnswerId(3);
answer.setDescription(3rd choice);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("answerList", answerList);
<select id="dropdown" name="dropdown">
<option value="">Select</option>
<c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
<option value="${answer.description}" label="${answer.description}"/>
</c:forEach>
</select>
or keep options as it is and in controller level you can get that value from dropdown request parameter (example: 3)
And after that you can loop the answer list (answerList) and find value in controller level.
<c:forEach items="${answerList}" var="answer" varStatus="answerStatus">
<option value="${answer.answerId}" label="${answer.description}"/>
</c:forEach>
Note
answer.answerId = 3
answer.description = 3rd choice
Related
I know the title might be misleading but here my question: In Thymeleaf we set request params with the input (in HTML). Is it possible to have an input field that sets the path variable. For example I have an method like this:
#PostMapping("/house/{id}/rent")
public String rentHouse(#RequestParam Date startDate, #PathVariable("id") long id, Model model) {
House h = new House();
h.setId(id);
r.setStartDate(startDate);
Rents rents = rentsService.createNewRent(h, id);
model.addAttribute("rent", rents);
return "House";
}
And in House.html I want something like this:
<form th:action="#{/house/${id}/rent/}" method="post">
<label for="startDate">start Date:</label><br>
<input type="datetime-local" id="startDate" th:name="startDate" placeholder="startDate"><br>
<label for="id">house id:</label><br>
<input type="number" id="id" th:name="id" placeholder="id"><br>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
So that when I input something then the result url should be looking like this (I know start Date has false format):
localhost:8080/House/12/rents?startDate=02.21.22
And is it also possible to pass request body in Thymeleaf, I searched for similar questions but they all solved it by manually putting the path variable in the url.
Thanks in advance
Here is my form html
<div class="card-body">
<form action="#{/orgCategoryTag/create}" method="POST">
<div class="form-group">
<label for="form-tags-1" class="text-dark font-bold">Add new tags</label>
<input id="form-tags-1" name="tags-1" type="text" th:value="${tags}">
</div>
<a
type="button"
class="btn btn-success" href="#"
data-placement="top" title="Tooltip on top">Add
</a>
</form>
</div>
Here is Get mapping for rendering form
#GetMapping(value = "/form")
public String categoryForm(Model model, BindingResult result) {
Long testId = (long)1;
OrgCategory orgCategory = new OrgCategory();
List<OrgCategoryTagModel> orgCategoryTags = orgCategoryTagRestController.getAllByCategoryId(testId);
model.addAttribute("category", orgCategory);
model.addAttribute("tags", orgCategoryTags);
model.addAttribute("add", true);
return "orgCategoryForm";
}
For displaying a list of options (tags in your context), please use a combo-box, they are better suited to display a list of options.
<select>
<option
th:each="tag: ${tags}"
th:text="${tag.name}"
th:value="${tag.id}"
/>
</select>
<select> is the tag for creating a combobox and <option> are the different options available in the combobox. I have used a for each loop to create different options for the combobox where tag represents your object OrgCategoryTagModel.
I do not know your object OrgCategoryTagModel, but I am assuming you want to display the name of the tag (tag.name) and use the id of OrgCategoryTagModel (tag.id) as the value to be saved when making a selection.
I have a form:
<f:form>
<f:select path="refmap" onchange="myMethod();" name="tableName" id="tableName" >
<f:options items="${valmap}"/>
</f:select>
<input type="submit" value="Submit" formAction="return constructUrl()"/></f:form>
Mentioned functions, but guess they aren't the big issue here:
function myMethod(){
var e = document.getElementById("tableName");
var tableName = e.options[e.selectedIndex].value;
}
function constructUrl(){
var e = document.getElementById("tableName");
var tableName = e.options[e.selectedIndex].value;
return "/spravochnik/list/"+tableName;
part of my controller leading to this page:
Map refmap = new LinkedHashMap<>();
refmap.put("tableMap", valmap);
mod.addAttribute("refmap", refmap);
mod.addAttribute("command", refmap);
valMap just has names of tables (that's what I'm using in dropdown);
The thing is, the jsp is swearing at me for refmap not having valid gettter/setter. I just want to pass along the dropdown value and nothing else. What backing object should I choose?
Can you do similar to this with your code and try ? It works for me.
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
I have a small problem, I just need to redirect to the value of select like:
/results/name/Heli Redel
How would I go about doing that?
<div class="search">
<select th:required="true">
<option th:value="'Eha Raudreha'" th:text="'Eha Raudreha'"></option>
<option th:value="'Heli Redel'" th:text="'Heli Redel'"></option>
<option th:value="'Mait Kuusevaik'" th:text="'Mait Kuusevaik'"></option>
</select>
<a class="buttons" th:href="#{|/results/name/NAME_HERE|}"><button class="deleteBtn">Otsi</button></a><br />
</div>
Add a jQuery function, that when the button is clicked, it redirects to a another url.
jQuery(document).ready(function() {
$('.deleteBtn').on('click', function() {
var selectValue = $('.search').find('select').val()
window.location.replace("/result/name/" + selectValue);
})
})
I would add some ids to your elements to make it easier to fetch data.
This question already has answers here:
How can I retain HTML form field values in JSP after submitting form to Servlet?
(2 answers)
Closed 6 years ago.
Out of the many solutions I've found, I can't seem to get any of them to work for me. I've got a dropdown list in my jsp file:
<select name="chosenOne" onchange="javascript:getUsers(this.value);">
<option value="0" onclick="javascript:getUsers(this.value);">All Modules</option>
<c:forEach items="${modules}" var="module">
<option value="${module.id}"><c:out value="${module.title}"/></option>
</c:forEach>
</select></p>
It populates dynamically from my database, except for the "All Modules" option. Here's my javascript function for the onchange event:
<script type="text/javascript">
function getUsers(id) {
if (id != "0"){
document.updateForm.id.value = id;
}
else{
document.updateForm.id.value = "0";
}
document.updateForm.submit();
}</script>
And here's my servlet code that deals with the dropdown box amongst other things:
protected void process(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
long modID = 0;
String url = "jsp/user/administration.jsp";
request.setAttribute("modules", dataAccessor.getAllModules());
if (isParameterValid(request.getParameter("id"))) {
modID = Long.parseLong(request.getParameter("id"));
request.setAttribute("users", getUsersFromModule(modID));
System.out.println(modID);
} else if (!isParameterValid(request.getParameter("id"))) {
request.setAttribute("users", dataAccessor.getAllUsers());
} else {
request.setAttribute("errorMessage", "There was a problem retrieving users!");
url = "jsp/error.jsp";
}
//request.setAttribute("formerSelect", modID);
request.getRequestDispatcher(url).forward(request, response);
}
So how can I get the selected dropdown value to remain in the dropdown box after the form refreshes? I've fiddled around with setting an attribute "formerSelect" which just contains the value of the previously selected item in the dropdown. But then for some reason it rendered my dropdown useless when I tried to assign it to the "selected" value within my options tag. Any help is much appreciated.
You need to pass this parameter to the httpRequest after submitting:
request.setAttribute("selectedModule", request.getParameter("chosenOne"));
and after that you need to mark an option as selected:
<c:forEach items="${modules}" var="module">
<option value="${module.id}" ${module.id == selectedModule ? 'selected':''}>...</option>
</c:forEach>
I can explain like this. As a example code
put this code in your Servlet
String status = request.getParameter("status");
request.setAttribute("status", status);
put this code in jsp file
<select id="status" name="status" class="listBx" onChange = "check(this);">
<option value="" >--- Select ---</option>
<option value="1" <%if((request.getAttribute("status") != null) && request.getAttribute("status").equals("1")){ %> selected <%} %>>Logged in</option>
<option value="0" <%if((request.getAttribute("status") != null) && request.getAttribute("status").equals("0")){ %> selected <%} %>>Logged Out</option>
</select>