user2999787
user2999787

Reputation: 637

save id´s of selected element´s

hey there i have little list here:

<ul id="selectable">
<li id='id.00'></li>
<li id='id.10'></li>
<li id='id.20'></li>
<li id='id.30'></li>
<li id='id.40'></li>
<li id='id.50'></li>
<li id='id.60'></li>
<li id='id.70'></li>
<li id='id.80'></li>
<li id='id.90'></li>
</ul

and i am able to select one or more of those listelement´s using css:

ul {overflow:hidden;}
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: black; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 300px; }
#selectable li {float: left; width: 30px; height: 20px; background-color: none; display:block; }

and now i want to save the id´s of all selected element´s using jquery:

$(function() {
    $( "#selectable" ).selectable({
        stop: function() {
            var result = $( "#select-result" ).empty();
            $( ".ui-selected", this ).each(function() {
                var index = $(this).attr('id');
                result.append( index );
                alert(index);
            });
        }
    });
});

ok so far so good: When i select e.g. four listelements, they get marked, BUT: only the last id is saved. For example, when i select this listelement´s:

<li id='id.00'></li>
<li id='id.10'></li>
<li id='id.20'></li>
<li id='id.30'></li>

only the id: "id.30" is safed in my variable "index". How can i get my jquery to safe all id´s of selected elements and not just the last one? greetings!

Upvotes: 0

Views: 337

Answers (1)

Try .map()

var result = $(".ui-selected", this).map(function () {
    return this.id;
}).get();

Note: This will return array


If you want to get string use .join()

var result = $(".ui-selected", this).map(function () {
    return this.id;
}).get().join(',');

Updated after OP's comment

fiddle Demo

$(function () {
    $("#selectable").selectable({
        stop: function () {
            var result = $(".ui-selected", this).map(function () {
                return this.id;
            }).get().join(',');
            $('#select-result').html(result);
        }
    });
});

Upvotes: 3

Related Questions