0

I am reordering (I know, un-ordered lists shouldn't have an order, but I wanted to use JQuery UI's sortable and it only worked with a ul) a list, each list item looks like below. The code to sort the list items is also below. My issue is that the selected option for each select tag is lost. Is there a way to move these elements around without losing this information? Do I need to keep track of it in javascript? This would be a pain since there is 3 selects per item.

<ul id="slotHtml"> <li class="energySlot"> <span class="energyHandle"></span> At <select class="startTime"> <option value="0">12:00 AM</option> <option value="23">11:00 PM</option> </select> enter <select class="sleepType" onchange="sleepTypeChange(this)"> <option value="wake"> Wake Up!!! </option> <option value="sleep"> Sleep!!! </option> <option value="deep"> Deep Sleep!!! </option> </select> <span class="inactivitySpan" style="display:none;"> after <!-- this is for sleep --> <select class="sleepAfter" style=""> <option>1</option> <option>3</option> <option>4</option> </select> <!-- this is for deep sleep --> <select class="deepSleepAfter" style="display:none;"> <option>1</option> <option>3</option> <option>5</option> </select> minute(s) of inactivity </span> <a class="energySaveEditorAdd" onclick="AddEnergySlot()">Add</a> <a class="energySaveEditorRemove" onclick="RemoveThisEnergySlot(this)">Remove</a> </li> </ul> 

here is my sorting code (javascript)

function SortSlots() { debugger; var slots = $('#energySlots').children(); var slotTimes = []; // add to map, also build array of the values. var slotMap = new Object(); for (var i = 0; i < slots.length; i++) { var timeVal = parseInt($(slots[i]).find('.startTime').val()); slotMap[timeVal] = $(slots[i]).wrap('<p/>').parent().html(); // wrap/unwrap to get the container in the html $(slots[i]).unwrap(); slotTimes.push(timeVal); } slotTimes.sort(sortNumber); var html = ''; for (var i = 0; i < slotTimes.length; i++) { html += slotMap[slotTimes[i]]; } $('#energySlots').empty(); $('#energySlots').append(html); } 
1
  • Unrelated to the question but change $(slots[i]) to slots.eq(i), much cleaner. Commented Feb 20, 2014 at 3:27

1 Answer 1

1

Work with the jquery objects and/or the dom elements, not the html strings.

slotMap[timeVal] = slots[i]; /* ... */ for (var i = 0; i < slotTimes.length; i++) { $('#energySlots').append(slotMap[slotTimes[i]]); } 
Sign up to request clarification or add additional context in comments.

1 Comment

This worked. Obviously had to make some changes to the algorithm other than what you listed. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.