Question

I have an unordered list of items - this list could be hundreds of items long - and as the user clicks an item, I display their selections to the right of the options. I'm using a combination of jQuery selectable and sortable to do so (although I lose the sortable once an option is clicked), and the value that is displayed for the user is the index of the selected item. I want to display the text value of the line item for the user instead, but as expected, grabbing the text() value returns the text values for all line items.

How can I grab just the selected text and display for the user?

HTML:

<ul id="list">
    <li id="Test1">Item 1</li>
    <li id="Test2">Item 2</li>
    <li id="Test3">Item 3</li>
    <li id="Test4">Item 4</li>
    <li id="Test5">Item 5</li>
</ul>

<p id="feedback">
<span>You've selected items:</span>    
    <ul id="select-result">
     <span id="select-resultSpan">
        <li>No Items Selected</li>
     </span>
    </ul>    
</p>

JS:

$(function () {
    $("#list").selectable({
        stop: function () {
            var result = $("#select-resultSpan").empty();
            $(".ui-selected", this).each(function () {
                var index = $("#list li").index(this);
                result.append("<li>" + (index + 1) + "</li>");
            });
        }
    });
});

Full example is on JSFiddle: http://jsfiddle.net/Jk6ZH/1/

Thanks in advance.

Was it helpful?

Solution

If I'm reading this right, think this is all you need:

$(".ui-selected", this).each(function () {

    // this works for me
    result.append("<li>" + $(this).text() + "</li>");
});

http://jsfiddle.net/JuJDt/

OTHER TIPS

Try this:

$("#list li").on("click",function() {
  $("#select-resultSpan").append($(this).text());
})
You have to find innerHTML from index value.
you can also get other attributes with this method.
$(function () {
        $("#list").selectable({
            stop: function () {
                var result = $("#select-resultSpan").empty();
                $(".ui-selected", this).each(function () {
                    var index = $("#list li").index(this);
                    var text = $("#list li").get(index).innerHTML; //  for id you can replace .innerHTML with .id 
                    result.append("<li>" + (text) + "</li>");
                });
            }
        });
    });

see here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top