'Create dropdown dynamically on select
I have a Many-to-Many-Relationship between FishingDay and Fisherman.
Here is my Entity-Class FishingDay:
@Entity
@Table(name = "FISHING_DAY")
public class FishingDay {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long fishingDayId;
@ManyToMany
@JoinTable(name = "fisherman_day",
joinColumns = @JoinColumn(name = "fishing_day_id"),
inverseJoinColumns = @JoinColumn(name = "fisherman_id"))
private Set<Fisherman> fishermen = new HashSet<Fisherman>();
// more properties, getter & setter ...
Here is my Entity-Class Fisherman:
@Entity
@Table(name = "FISHERMAN")
public class Fisherman {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long fishermanId;
@JsonIgnore
@ManyToMany(mappedBy = "fishermen")
private Set<FishingDay> fishingDays = new HashSet<FishingDay>();
// more properties, getter & setter ...
The Add- and Edit-Methods of FishingDay-ControllerClass:
public static final String FORM_NAME_SINGLE = "FishingDaySingleList";
private static final String REDIRECT_URL = "redirect:/fishingDays/show";
@GetMapping("/add")
public ModelAndView add()
{
LOGGER.info(LogUtils.info(CLASS_NAME, "add"));
ModelAndView mv = new ModelAndView(FORM_NAME_SINGLE);
mv.addObject("add", true);
mv.addObject("fishingDay", new FishingDay());
List<Fisherman> fishermen = fishermanRepository.findAll();
mv.addObject("fishermen", fishermen);
return mv;
}
@GetMapping("/edit/{fishingDayId}")
public ModelAndView edit(@PathVariable long fishingDayId) {
LOGGER.info(LogUtils.info(CLASS_NAME, "edit", String.format("%d", fishingDayId)));
ModelAndView mv = new ModelAndView(FORM_NAME_SINGLE);
Optional<FishingDay> optionalFishingDay = fishingDayRepository.findById(fishingDayId);
if (optionalFishingDay.isPresent()) {
FishingDay fishingDay = optionalFishingDay.get();
List<Fisherman> fishermen = fishermanRepository.findAll();
mv.addObject("add", false);
mv.addObject("fishermen", fishermen);
mv.addObject("fishingDay", fishingDay);
}
return mv;
}
@PostMapping(value = "/addEdit")
public ModelAndView addEdit(@Valid @ModelAttribute FishingDay fishingDay, BindingResult bindingResult) {
boolean error = false;
LOGGER.info(LogUtils.info(CLASS_NAME, "addEdit", String.format("%s %b", fishingDay, error)));
ModelAndView mv = new ModelAndView();
if (!error) {
error = bindingResult.hasErrors();
}
if (!error) {
try {
fishingDayRepository.save(fishingDay);
mv.setViewName(REDIRECT_URL);
}
catch (Exception e) {
e.printStackTrace();
LOGGER.error(LogUtils.info(CLASS_NAME, "addEdit"));
mv.addObject("error", e.getCause().getCause().getLocalizedMessage());
error = true;
}
}
else {
mv.setViewName(FORM_NAME_SINGLE);
mv.addObject("add", fishingDay.getFishingDayId() == null);
}
return mv;
}
Here is the FishingDaySingleList:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title th:text="#{fishingDay.caption.plural}"></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#" th:action="@{/fishingDays/addEdit}"
th:object="${fishingDay}" method="POST" enctype="application/x-www-form-urlencoded"
class="row g-3 needs-validation" novalidate>
<table id="table1" class="table table-striped table-responsive-md">
<tr>
<td th:text="#{fishingDay.fishingDayId}"></td>
<td><input type="text" th:field="*{fishingDayId}" size=10 readonly class="form-control"></td>
</tr>
<tr>
<td th:text="#{fishingDay.fishingDate}"></td>
<td><input type="date" th:field="*{fishingDate}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('fishingDate')}" th:errors="*{fishingDate}">
FishingDate Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.waterTemperature}"></td>
<td><input type="text" th:field="*{waterTemperature}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('waterTemperature')}"
th:errors="*{waterTemperature}">WaterTemperature Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.sunrise}"></td>
<td><input type="time" th:field="*{sunrise}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('sunrise')}" th:errors="*{sunrise}">Sunrise
Error
</td>
</tr>
<tr>
<td th:text="#{fishingDay.sunset}"></td>
<td><input type="time" th:field="*{sunset}" size=50 placeholder="" class="form-control"></td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('sunset')}" th:errors="*{sunset}">Sunset
Error
</td>
</tr>
<tr>
<td th:text="#{fisherman.caption.singular}"></td>
<td>
<select class="form-control" id="fishermen" th:field="*{fishermen}" oninput="showStuff()">
<option value="-1" th:text="#{option.choose}"></option>
<option th:each="fm:${fishermen}"
th:value="${fm.fishermanId}"
th:text="${fm.fullName} + ' (' + ${fm.nickname} + ')'"
th:id="fmId">
</option>
</select>
</td>
<td class="alert alert-danger" th:if="${#fields.hasErrors('fishermen')}" th:errors="*{fishermen}"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="btn btn-primary" th:value="#{button.save}"/></td>
</tr>
</table>
<p class="alert alert-danger" th:if="${error!=null}" th:text="${error}"></p>
</form>
</div>
</body>
</html>
Everything is working fine, but I want to create the same dropdown dynamically after a value is selected and append it to the previous dropdown. Moreover, after every selection the value should be removed from list. This should be done until submit or the list is empty.
Here is an image for demonstration
I guess it is possible with javascript? But I've never had anything to do with it before and that's why I run into many troubles when I try to realize this on my own.
Solution 1:[1]
Yes, JavaScript can handle this. Try this one:
<select name="val" size="1" id="fishermen" onchange="doSomething();">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<script>
function doSomething() {
var selectedFisherman = document.getElementById("fishermen");
for (var i=0; i<selectedFisherman .length; i++) {
if (selectedFisherman.options[i].value == selectedFisherman.value) {
selectedFisherman[i].setAttribute("hidden", "hidden");
}else {
selectedFisherman[i].removeAttribute("hidden");
}
}
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | paranaaan |