Miljac Miljac - 1 year ago 104
Java Question

How to submit selected items only from jQuery-ui selectable to java spring controller

I have working controller and jsp with form which submits all elements of some list back to controller.

I would like to submit only selected items of jQuery-ui selectable to spring controller.

My .jsp looks like this:

<!-- jQuery rference -->
<script src="<c:url value="/resources/jquery-2.1.1.js" />"></script>
<!-- jQuery-ui reference -->
<script src="<c:url value="/resources/jquery-ui-1.11.2.custom/jquery-ui.js" />"></script>
$(function() {$("#selectable").selectable();});
<!-- context path -->
<c:set var="contextPath" value="${pageContext.request.contextPath}" />

<form:from action="${contextPath}/user/categories/delete" method="POST" modelAttribute="categoryList">
<input type="submit" value="Delete Selected" />
<ol id="selectable">
<c:forEach items="${categoryList.catList}" var="category" varStatus="status">
<li class="ui-widget-content" value="${category}">${}</li>
<input type="hidden" name="catList[${status.index}].id" value="${}" />
<input type="hidden" name="catList[${status.index}].name" value="${}" />

And here is controller:

public class CategoriesController {

private CategoryDetailService categoryDetailService;

public String deleteCategory(@ModelAttribute("categoryList") CategoryList categoryList) {
//do something
return "redirect:/user/categories";

Is there a way to submit only selected items back to controller?

Answer Source

After reading a lot about jQuery and JSTL best thing I came up with is adding jQuery function which clears unselected dom elements. I have used empty function, but .remove() also does the trick.

$(function() {
    $("#categorySubmit").button().click(function(event) {
        $(function() {
            $("#selectable li:not(.ui-selected)", this).each(function() {

where "#categorySubmit" is id given to submit button with name "Delete category"

You have to be careful tough, because only elements with index greater than last selected element are removed, elements with lower index which are not selected have property values set to null (or 0), for both .empty() and .remove().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download