javascriptmultiple-select

Creating buttons from Multiple Select Value in Javascript


I am working on a website where teachers can create questions and question pages and student can log in and answer them. Now in the teacher interface, when creating the question the teacher can see how the question will appear in the student interface. For that I use javascript to get my form data and display it in real time. The problem I had was with a multiple select, it is supposed to be question labels that appear in the form of buttons in the student interface, but whenever I select more than an option, is is not only the button for the last selected option that is created, but buttons for all the selected options every new select.

$("#etiquettes").on('change', function() {
        var affiche= [];
        const myDiv = $("#etiquette-display");
        for (var option of document.getElementById("etiquettes")) {
            if (option.selected && (!affiche.includes(option.value))) {
                let html = '<button class="button is-info" type="button">'+option.value+'</button>';
                myDiv.append(html);
                affiche.push(option.value);
            }
        }
    });

I tried creating the affiche array and add in it every option that was selected and it's button created so that when I loop over all the selected options, the ones whose buttons were created don't get created again. But it doesn't seem to work!


Solution

  • You have to empty myDiv every time multiselect changes.

    $("#etiquettes").on('change', function() {
        var affiche= [];
        const myDiv = $("#etiquette-display");
        myDiv.empty();
        for (var option of document.getElementById("etiquettes")) {
            if (option.selected && (!affiche.includes(option.value))) {
                let html = '<button class="button is-info" type="button">'+option.value+'</button>';
                myDiv.append(html);
                affiche.push(option.value);
            }
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="etiquettes" multiple>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <div id="etiquette-display"></div>