I am trying to insert a comma-separated list into the DOM, which the user can copy and paste into another application. Right now, I'm completely fixated on how to handle the first element, which is not preceded by a comma.
Now the user clicks on the element, and jquery captures the identifier of the element to create a list. The user should be able to turn their selections on and off. I also need a list that should be generated in the order in which the user selects the items.
HTML
Comma separated list here: <span id="list"></span> <br /> <a id="1" class="clickme" href="#"><li>One</li></a> <a id="2" class="clickme" href="#"><li>Two</li></a> <a id="3" class="clickme" href="#"><li>Three</li></a> <a id="4" class="clickme" href="#"><li>Four</li></a> <a id="5" class="clickme" href="#"><li>Five</li></a> <a id="6" class="clickme" href="#"><li>Six</li></a>
CSS
.selected { background-color: #99CCFF; }
JS-jquery loaded
$('.clickme').click(function (e) { e.preventDefault(); var book_id = $(this).attr('id'); $(this).children('li').toggleClass("selected"); var list_container = $("#list"); if ($(this).children('li').is(".selected")) { if (list_container.text().length > 0) { list_container.append("," + book_id); } else { list_container.append(book_id); } } else { list_container.text(list_container.text().replace("," + book_id, "")); } });
This works great to create a comma separated list, and it works great to disable everything except the first value in the list. The problem is that the first value was inserted without the preceding comma, and therefore the replace function cannot match it. If I remove the comma from the replace function, I will be left with a bunch of unnecessary commas. If I match both, then I risk matching part of the identifier ... i.e. Replace 3 with 13 when 3 switches.
I tried a lot of variations and can not find anything that works.
My only solution, which gave the desired result, was to use CSS to enter commas and wrap the entered identifiers with a span element.
CSS TRICK
#list span { display: inline; } #list span:after { content: ","; } #list span:last-child:after { content: ""; }
Worked perfectly ... except for the actual purpose of this. I need so that users can copy and paste the generated string. When you use CSS to create content, most browsers donβt see this in the DOM-level clipboard. IE copied the string as you see it in the browser, FF and Safari copied the string without added CSS commas.
Fiddle is HERE