0

I have a function that adds badges to a div by selecting items from a dropdown list.

I'm adding badges using this function added to the dropdown list onclick event:

function addBadge(parent, badgeId, value){
    var elem = document.getElementById(parent);

    var currentTaxiways = elem.children;
    var alreadyExists = false;

    for(var i = 0; i < currentTaxiways.length; i++){
        if(badgeId === currentTaxiways[i].id){
            alreadyExists = true;
        }
    }

    if(!alreadyExists) {
        var newBadge = document.createElement("span");
        newBadge.classList.add("badge");
        newBadge.classList.add("badge-primary");
        newBadge.classList.add("bg-secondary");

        newBadge.id = badgeId;

        var node = document.createTextNode(value);
        newBadge.appendChild(node);

        newBadge.innerHTML += "&emsp;";

        var deleteButton = document.createElement("a");
        deleteButton.href = "#";
        deleteButton.classList.add("x-btn");
        deleteButton.onclick = function delBadge() {
            deleteBadge(newBadge.id);
        };

        var node2 = document.createTextNode("X");
        deleteButton.appendChild(node2);

        newBadge.appendChild(deleteButton);

        elem.appendChild(newBadge);
    }
}

And the function for deleting the badges is this one:

function deleteBadge(badge){
    var elem = document.getElementById(badge);
    elem.parentNode.removeChild(elem);
}

How do I send the list of ids of all the badges added to the div to my controller using thymeleaf when the form is submitted?

V. Pantis
  • 105
  • 1
  • 7
  • 2
    The easiest approach I could think of is to add a with a value matching your span. As hidden inputs are also FORM elements, they will be sent via form submission. In your controller, you can use an appropriate model object to get the list. – Raja Anbazhagan Sep 09 '21 at 12:12
  • This question addresses a problem that is somewhat similar to yours. https://stackoverflow.com/questions/48499723/thymeleaf-list-within-list-input – Raja Anbazhagan Sep 09 '21 at 12:15
  • You don't "use Thymeleaf" to send data from a web page form to your server. Thymeleaf only exists on the server. Its purpose is to replace itself with regular HTML _before_ the page is sent to the browser. – andrewJames Sep 09 '21 at 12:51
  • @RajaAnbazhagan is it possible to send the hidden inputs as an array mapped to a List field of a class? – V. Pantis Sep 09 '21 at 14:10
  • @V.Pantis Yes. But you need to match the `th:field` attribute to match the model object. – Raja Anbazhagan Sep 10 '21 at 14:23

0 Answers0