Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Making a list item sortable

Hi guys, im trying to make the items on my shopping list sortable. i tried writing the code two different ways but none of them work. Also the check box only shows up for the first item and not any other items that the user adds. any ideas how to fix it? http://codepen.io/mbrwn/pen/QbePRd

4 Answers

Ahhh, in that case, change your add_button click code to this:

$("#add_button").click(function(){
    var toAdd = $('input');
    var listCount = $('ul').find('li').length;
    var html = '';

    html += '<li><input type="checkbox" value="None" id="checked';
    html += listCount;
    html += '" name="check';
    html += listCount;
    html += '"><span>';
    html += toAdd.val();
    html += '</span></li>';

    $('ul').append(html);
    toAdd.val("");
});

Since you can't have more than 1 item with the same ID, I added that listCount variable so that as you add more items to the list, the IDs will come out like this

  • checkbox1
  • checkbox2
  • checkbox3

and so on

The checkbox is in your HTML. Just remove it.

<!--
<li><input type="checkbox" value="None" id="checked" name="check"><span>test</span></li>
-->
<li>test</li>

As for making things sortable, the easiest solution might be to use a plugin like these for example

http://farhadi.ir/projects/html5sortable/

https://jqueryui.com/sortable/

The plugin that you choose will have instructions for how to use it.

sorry maybe i wasnt very clear. i dont want to remove the checkboxes i want them for every input that the user puts in but currently. it only has a checkbox on the first item. everytime the user adds a item after that it doesnt add the check box.

thank you