Pergunta

I have two lists which are sortable and then a button. The user adds items from the first list to the second list and then when they click the button I have some script collect the list item id's from the second list. This part works as intended.

My problem comes when the user accidentally adds an item to the second list that they want to remove. I have a trash can icon that works to removes the item from the list, but then when you hit the button to get the array, it still includes the deleted list item in the array. How do I avoid this? Should I be building the array as the items are added and removed, or is it OK to only build it once after they are done moving list items around like I have done here?

Thanks for taking a look!

http://jsfiddle.net/vYu5k/

    <div class="avail_segments_wrap">
    <ul id="available" class="segments_available">Available Segments
        <li id="1"><span class="title">Item 1</span><a href="#" class="ui-icon ui-icon-add"></a></li>
        <li id="2"><span class="title">Item 2</span><a href="#" class="ui-icon ui-icon-add"></a></li>
        <li id="3"><span class="title">Item 3</span><a href="#" class="ui-icon ui-icon-add"></a></li>
        <li id="4"><span class="title">Item 4</span><a href="#" class="ui-icon ui-icon-add"></a></li>
        <li id="5"><span class="title">Item 5</span><a href="#" class="ui-icon ui-icon-add"></a></li>
        <li id="6"><span class="title">Item 6</span><a href="#" class="ui-icon ui-icon-add"></a></li>
    </ul>
</div>

<br>

<div class="chosen_segments_wrap">
    <ul id="chosen" class="segments_chosen">Chosen Segments
    </ul>
</div>

<button type="button" id="button1">Button1</button>

jquery:

//make lists sortable
$("#available").sortable({
    connectWith: "#chosen"
});
$("#chosen").sortable({
    connectWith: "#available"
});

//make add and trash icons functional
$('.ui-icon-add, .ui-icon-delete').on('click', function() {
    item = $(this).parent();
    item.fadeOut(function() {
        if (item.parent().attr('id') == 'chosen') {
            $('#available').remove(item.fadeIn());

        } else {
            $('#chosen').append(item.fadeIn());
        }
    });
});

//hit button to collect all li id's from ul "chosen".
$("#button1").click( function()
           {
             var chosenArray = [];
                $('#chosen li').each(function(){
                chosenArray.push($(this).attr('id'));
                    });
               alert(chosenArray)
           }
        );
Foi útil?

Solução

Fiddle Demo

$("#button1").click(function () {
    var chosenArray = [];
    $('#chosen li:visible').each(function () {


You are hiding the li on delete. But when you create array you are taking all li elements

you need to select only visible elements $('#chosen li:visible').

Read   :visible

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top