Home > Software engineering >  asp.net bootstrap select list-group box remove items
asp.net bootstrap select list-group box remove items

Time:04-28

I have a drop down and a list group box. on the drop down change event I need to remove all the items and add new items.

Below is the list group box

  <select style="max-height: 30vh; min-height: 30vh; width: 100%; border: 0;"
                        multiple="multiple"
                        >
                    @foreach (var listGroupOption in Model.OrderItems ?? new List<SelectListItem>())
                    {
                        <option value="@listGroupOption.Value" >
                            @listGroupOption.Text
                        </option>
                    }
                </select>

This is my try at JavaScript

$('#ddlRegion').change(function (e) {

            $(".list - group - available - items")
                    .find('option')
                    .remove();
        });

CodePudding user response:

In simple remove, we can try to use empty all of option

$(".list-group-available-items").empty();

or use remove by option like

$(".list-group-available-items option").remove();

if we need to append new option after remove all option we can try to use append

$(".list-group-available-items option").remove();

$(".list-group-available-items").append($('<option>', { 
        value: 'newOption',
        text : 'newOption' 
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select >
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
</select>

CodePudding user response:

You need to first empty the existing list with .empty() and then append new options with append():

const myButton = document.getElementById('btn');
        myButton.addEventListener('click', function(){
            $(".list-group-available-items").empty();
            $(".list-group-available-items").append('<option value="newval1">New Item 1</option>');
            $(".list-group-available-items").append('<option value="newval2">New Item 2</option>');
            $(".list-group-available-items").append('<option value="newval3">New Item 3</option>');
        });
  • Related