简体   繁体   English

在选择时动态创建下拉列表

[英]Create dropdown dynamically on select

I have a Many-to-Many-Relationship between FishingDay and Fisherman.我在 FishingDay 和 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: 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:这是 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?我想这可以用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.但我以前从未与它有任何关系,这就是为什么当我试图自己意识到这一点时会遇到很多麻烦。

Yes, JavaScript can handle this.是的,JavaScript 可以处理这个问题。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM