0

I have been given a task of moving items between two checkbox lists it should work such that when checkbox in one list is checked it should be removed from the list and added to second list. Similarly if checkbox in second list is checked it should be removed from that list and added back to first list.

I have written the following code i was expecting it to work but when a checkbox is checked it is appended to the bottom of the same list in which it was checked and only after it is checked twice it gets removed from the list and added to another list. Please help me find what the problem is `

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MovingItems.aspx.cs" Inherits="MyFirstProject.MovingItems" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        #list1{
            border:7px solid red;
        }
        #list2{
            border:7px solid blue;
        }
       </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:CheckBoxList ID="list1" runat="server" onchange="moveCheckbox(event, 'list1', 'list2')">
  <asp:ListItem Text="Item 1" Value="1" />
  <asp:ListItem Text="Item 2" Value="2" />
  <asp:ListItem Text="Item 3" Value="3" />
</asp:CheckBoxList>

<asp:CheckBoxList ID="list2" runat="server" onchange="moveCheckbox(event, 'list2', 'list1')">
    <asp:ListItem Text="Item 5" Value="0" />
</asp:CheckBoxList>

<script>
    function moveCheckbox(event) {
        var checkbox = event.target;
        var listItem = checkbox.parentNode;
        var fromList = listItem.parentNode;
        var toList = (fromList.id === 'list1') ? document.getElementById('list2') : document.getElementById('list1');
        if (checkbox.checked && fromList.contains(listItem)) {
            fromList.removeChild(listItem);
            toList.appendChild(listItem);
            c
        }
    }

</script>








        </div>
    </form>
     <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>


         
</body>
</html>

  • The code only moves the list item if it is checked, but the handler runs before that has happened. I’d think doing the remove/append stuff without regard for the checked state would work. – padeso Apr 06 '23 at 11:53
  • I have tried that also that doesn't change anything – huzaifa Bilal Apr 06 '23 at 17:07
  • Ok. Because the handler is attached to the `asp:CheckBoxList`, the `event.target` is the `select` element, not one of its `option`s, so the following code won't work. You can get information about finding the selected item here: https://stackoverflow.com/questions/5416767/get-selected-value-text-from-select-on-change – padeso Apr 07 '23 at 12:14

0 Answers0