0

How to select a certain clone of list using jquery?

 <ul id=testList>
      <li><input type=checkbox" /><p> Test A </p></li>
      <li><input type=checkbox" /><p> Test B </p></li>
      <li><input type=checkbox" /><p> Test C </p></li>
      <li><input type=checkbox" /><p> Test D </p></li>
      <li><input type=checkbox" /><p> Test E </p></li>
 </ul>

     var $cloneList = $("#testList").clone();

     $cloneList.find("li input:checked")each(function()
     {
          alert($(this.outerHTML);
     });

The output I'm trying to accomplish with this jquery code above is listed below by only selecting the checkboxs that has been selected and remove input tags:

    <li><p> Test E </p></li>
Joseph Walker
  • 207
  • 1
  • 4
  • 13

1 Answers1

0

To get exactly what you ask for, the code would be something like this:

$(document).ready(function(){
    $('#clone').click(clone);
});

function clone(){
    clonedList = $('#testList').clone();
    clonedList.find('input[type=checkbox]:not(:checked)').each(function(){
        $(this).parent().remove();
    });
    clonedList.find('input').remove();
    alert(clonedList.html());
}

Check out the working fiddle: http://jsfiddle.net/Kh476/3/

One thing I'd like to point out - those checkboxes without proper labels drive me nuts. Do this instead:

<label><input type="checkbox" name="group1" value="A"/> Check This A</label>    ​

This will allow screen readers to figure out which text goes with which checkbox and it will also allow people to click on the text as opposed to having to find the box to click on. Much more usable.

To get the outerHtml, check this answer: Get selected element's outer HTML

Community
  • 1
  • 1
Milimetric
  • 13,411
  • 4
  • 44
  • 56