0

I am new using Jquery. I've been working around this matter without any solution, So I will appreciate any help.

I have two listboxes (lstbox1 and lstbox2) in HTML and I am using Jquery to pass values from one listbox to another. The problem with this code, is that once I moved an option from lstbox1 to lstbox2 and I click over the option again to return it back nothing happens. Once, I move an option from lstbox1 or lstbox2, I can't return it to its previous position.

$(document).ready(function() {
   
 $("#lstBox1 option").click(function () {
   var selectedOp1 = $('#lstBox1 option:selected');
   $('#lstBox2').append($(selectedOp1).clone());
        $(selectedOp1).remove();
    });

    $("#lstBox2 option").click(function () {
   var selectedOp2 = $('#lstBox2 option:selected');
   $('#lstBox1').append($(selectedOp2).clone());
        $(selectedOp2).remove();
    });
 
 
 
});
#lstBox1 {
 width: 200px;
 height: 200px;
}
#lstBox2 {
 width: 200px;
 height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style='width:370px;'>
    <tr>
        <td style='width:260px;'>
            <b>Group 1:</b><br/>
           <select multiple="multiple" id='lstBox1'>
              <option value="1">Ajax</option>
              <option value="jquery">jQuery</option>
              <option value="javascript">JavaScript</option>
              <option value="mootool">MooTools</option>
              <option value="prototype">Prototype</option>
              <option value="dojo">Dojo</option>
        </select>
    </td>
    
    <td style='width:260px;'>
        <b>Group 2: </b><br/>
        <select multiple="multiple" id='lstBox2'>
        <option value="C#">C$</option>
        <option value="Java">Java</option>
        <option value="HTML">HTML</option> 
        </select>
    </td>
</tr>
</table>
Polonio
  • 23
  • 4
  • You need to use delegated event handlers as you're effectively creating new elements when you append and clone them between lists. See the duplicate I marked for more information – Rory McCrossan Nov 04 '18 at 18:26
  • Thank you Rory for your answer. I wish I could understand you. Remember I am new to this. – Polonio Nov 04 '18 at 19:01

1 Answers1

0

Instead of adding click event on #lstBox2 option add only on the #lstBox2.

Updated code

$(document).ready(function() {

    $("#lstBox1").click(function () {
         var selectedOp1 = $('#lstBox1 option:selected');
         $('#lstBox2').append($(selectedOp1).clone());
        $(selectedOp1).remove();
    });

    $("#lstBox2").click(function () {
         var selectedOp2 = $('#lstBox2 option:selected');
         $('#lstBox1').append($(selectedOp2).clone());
        $(selectedOp2).remove();
    });



});
front_end_dev
  • 1,998
  • 1
  • 9
  • 14