Announcement

Tuesday, 18 March 2014

Add items from one drop down to another drop down using jquery

1. Define a function that will move items from one drop down to another drop down.

2. This function will be called on the click of buttons i.e., Button for removing item and Button for       adding item.

3. The function accepts two parameters i.e., fromDropdown and toDropdown. It will move items           from fromDropdown to toDropdown.

4. The .off() method removes event handlers that were attached with .on(). See the discussion of         delegated and directly bound events on that page for more information. Calling .off() with no           arguments removes all handlers attached to the elements. Specific event handlers can be                 removed on elements by providing combinations of event names, namespaces, selectors, or             handlers function names.
 
    It basically removes an event handlers. For more information Click here.

Function for adding and removing items from one drop down to another drop down.

   function cutAndPaste(from, to) {
        $(to).append(function () {
            return $(from + " option:selected").each(function () {
                this.outerHTML;
            }).remove();
        });
   }

On click of Add button.

    $("#btnAdd").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#fromDropDown").val();
        e.preventDefault();
        $("#toDropDown option").each(function () {
            if ($(this).val() == txt) {
                itemExists = true;
                alert('Items already exists.');
                return false;
            }
        });
        if ($('#fromDropDown').val() == null) {
            alert('Item list is empty.')
        }
        if (!itemExists) {
            cutAndPaste("#fromDropDown", "#toDropDown");
        }
    });

On click of Remove button.

    $("#btnRemove").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#toDropDown").val();
        e.preventDefault();
        if ($("#toDropDown :selected").val() > 0) {
            cutAndPaste("#toDropDown", "#fromDropDown");
        }
        else {
            alert('Item does not exists');
            return false;
        }
    });

No comments: