Ra3IDeN Ra3IDeN - 20 days ago 6
Javascript Question

How to detect option deselect with jquery?

I have a list of options. When selectting an option in the list I create new elemets and append them to another div.

HTML:

<select multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

<div class="tankListProduct">
// things get appended here
</div>


Script

$(function(){

$("#SelectedProduktValues")
.on("change", function(e) {
var optionValueArray = $(this).val();
var optionValue = optionValueArray[optionValueArray.length-1];
var optionText = $("#SelectedProduktValues option[value='" + optionValue + "']").text();

var $options = $("#SelectedTanksValues > option").clone();

var div = "<div class='col-xs-20 adminRow'>";
div += "<p class='col-xs-20 text-center'>" + optionText + "</p>";
div += "<select class='form-control tankList'</select>";
div += "</div>";

$(".tankListProduct").append(div);

$('.tankList').last().selectpicker();
});
})


This works perfectly and is shown in the fiddle below but I can't figre out how I can detect if an option in the list has been deselected so that I can remove the inserted element that corresponds to that option?

Fiddle

EDIT:

If it was uncelar, this is a multiSelect list

Answer
  1. You forgot to close the select tag.
  2. Clearing the html before you append should help "deselect" the no longer selected ones.
  3. And a jQuery each loop to loop over the selected elements.

$(function () {

$("#SelectedProduktValues")
  .on("change",
    function (e) {

        var optionValueArray = $(this).val();

        if (optionValueArray != null) {
            var div = '';
            $.each(optionValueArray, function (key, value) {
                var optionValue = value;
                var optionText = $("#SelectedProduktValues option[value='" + optionValue + "']").text();

                div += "<div class='col-xs-20 adminRow'>";
                div += "<p class='col-xs-20 text-center'>" + optionText + "</p>";
                div += "<select class='form-control tankList'> </select>";
                div += "</div>";
            });

            $(".tankListProduct").html('');
            $(".tankListProduct").append(div);

            $('.tankList').last().selectpicker();
        }

        else
            $(".tankListProduct").html('');
    });

})

And here's a fiddle.

https://jsfiddle.net/uhnkwx1g/8/

Hope this helps.