Insert alphabetically with jQuery

I was working on a single page for a work job that involved saving and loading data without reloading the page. To do this I had to insert values into drop down lists (two fo them, one for loading and one for deleting). Initially I was just going to add a group at the bottom, but it seemed like a cheap way to go, so I created a script to add the items in the existing lists where they belong. All these list were alphabetical, so it was really simple. The code below is a derivative of my original drop down menu modification code that places items in an ordered list, except it:

  • ‘+name+’

  • ‘+name+’


The code works in four parts, first we get the new item, in this case it’s the contents of a text field, and we make sure it’s not blank. Then we go through the list in question, in this case it’s at il.thelist and go through each item one my one. Then we get the value of the list item and compare it to the value of the item were adding. It’s no problem to compare string, it works the same was as comparing numbers, the only think to note is that capitals and lower case letter have different “values” so to speak so to get try alphabetization you must capitalize (or lowercase, it shouldn’t matter) both the string when comparing. Finally you insert the item before the first hit, and set variable so that it won’t continue to add it after every item from that point on. You also need to have one final check against that variable, so if it was never added to the list (as it in there is nothing that would come after it, given how it’s being checked) then it can go to the end of the list (because at this point it’s the only place left that it could possibly belong in).

I’ve set up a jQuery insert alphabetically example if your interested, I can also answer any questions you have, just leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *