jQuery Selectable Get Text Value

廉价感情. 提交于 2019-12-12 02:24:29

问题


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.


回答1:


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/




回答2:


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




回答3:


Try this:

$("#list li").on("click",function() {
  $("#select-resultSpan").append($(this).text());
})


来源:https://stackoverflow.com/questions/15621111/jquery-selectable-get-text-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!