Grizzly
Grizzly

Reputation: 5953

jQuery Removing Items From DropDownList

On my view I have a dropdownlist that uses Select2, a blank ul element, and a hidden ListBox Element. The Listbox element is what is being submitted to the server.

<div class="form-group">
    @Html.Label("Grade", new { @class = "control-label col-md-2" })
    <div class="col-md-5">
        @Html.DropDownList("IPGrade", null, "-- Select a Grade --", new { id = "Grade-DDL", @class = "form-control" })
    </div>
    <div class="col-md-3">
        <ul id="Grade-List" class="list-group"></ul>
    </div>
</div>

@Html.ListBoxFor(model => model.LstGrades, new List<SelectListItem>(), new { id = "Grades-ListBox", @class = "form-control" })

Now, when the user selects an option from the dropdownlist, that value is being populated into the ul element and the Listbox element via jQuery. When the element is being added to the ul element, I am also creating a btn that allows the user to remove the item from the ul and the Listbox. Herein lies the problem.

The user has the ability to select the same option in the dropdownlist however many times they choose, so if they select Option 1 from the dropdownlist 3 times.. then the ul element and the Listbox element will have Option 1 3 times. But, if the user selected Option 1 one too many times and they want to remove one from the ul so they are still left with 2 is where my problem is.

When the user tries to remove an option that is repeated in the ul element.. when they click remove.. it removes ALL options that are the same as the one that is being repeated. So in the example above.. if the user tried to delete one of the Option 1.. then it will delete all 3 Option 1.

Here is my jQuery.

Adding items to UL and Listbox

$("#Grade-DDL").on("select2:select",
    function(evt) {
        console.log(evt.params);
        $("#Grade-List").append("<li class='list-group-item' data-id='" +
            evt.params.data.id +
            "' >" +
            evt.params.data.text +
            " <input type='button' class='btn btn-default btn-xs remove-button' style='float: right; margin-top: -2%;' value='x' /></li>");
        $("#Grades-ListBox")
            .append("<option selected='true' value='" +
                evt.params.data.id +
                "'>" +
                evt.params.data.text +
                "</option>");
        $("#Grade-DDL").val("").change();
    });

Removing items from UL and Listbox

function removeGradeCapability() {
    $("#Grade-List").on("click",
        ".remove-button",
        function () {
            //alert($(this).parent().text());
            //alert($(this).parent().data("id"));
            var elementId = $(this).parent().data("id");

            $("#Grades-ListBox option[value='" + elementId + "']").remove(); // remove item from listbox
            $(this).parent().remove(); // remove item from ul element
        });
}

Goal

Only remove that single option that the user is selecting, even if that option is repeated in the ul element...

Any help is appreciated.

Updated Fiddle

Here is a replica of what exactly my problem is!

My Fiddle

Upvotes: 2

Views: 108

Answers (1)

2oppin
2oppin

Reputation: 2001

Seems your options have same values, so sure thing, selecting them by value you'll delete em all,

you need to add some unique identifier to your options, or even better - add handler to the element right in creation time.

Something like this should work:

function(evt) {
  console.log(evt.params);
  $("#Grade-List").append(
    $("<li class='list-group-item' data-id='" + evt.params.data.id + "' >" + evt.params.data.text + " </li>")
        .append(
            $("<input type='button' class='btn btn-default btn-xs remove-button' style='float: right; margin-top: -2%;' value='x' />")
                .click(function(e){
                    $(e.target).closest('option').remove();
                })
        )
  );
  $("#Grades-ListBox")
    .append("<option selected='true' value='" +
        evt.params.data.id +
        "'>" +
        evt.params.data.text +
        "</option>");
  $("#Grade-DDL").val("").change();
});

About ID :

var usedIDs = [];
// as a concept only
function generateId() { 
  let id = ('' + (new Date()).getTime() + (1000* Math.random())).replace('.', '');
  return usedIDs.indexOf(id) == -1 ? id : generateId();
}

then in your select:

let uid = generateId();
$("#Grade-List").append('<li ...tradada ... ' + 'data-uid="' + uid + '"... tradada ... </li>');
$("#Grades-ListBox").append("<option ...tradada ... ' + 'data-uid="' + uid + '"... tradada ... </option>');

finaly on delete-click:

$('[data-uid="' + $(e.target).data('uid')+ '"]').remove()

Upvotes: 1

Related Questions