Skyalchemist
Skyalchemist

Reputation: 461

Perform an action when an li is the last in the ul

I have this http://jsfiddle.net/mDfQT/15/

<ul id="variants" data-size="0">
    <input type="text" id="some_name" class="some_name" placeholder="category name">
</ul>
    <a href="#" class="add_options" data-id="70281696560900">Add more </a>
Number of rows: <span id="count">0</span>

So the JavaScript displayed in the fiddle appends an li with a textbox when the add more link is clicked and also removes it when the remove link is clicked.

When I click the remove link I want to check if that's the last li in the ul and if it's the last/only li I want to also remove the input with id some_name.

How would you go about this?

Upvotes: 0

Views: 105

Answers (1)

adeneo
adeneo

Reputation: 318202

$('.add_options').on('click', function () {
    if ( $('#variants > li').length < 2 && (! $('#some_name').closest('li').is(':visible') )) {
        $('#some_name').closest('li').show();
    }else{
        var li  = $('<li />',    {'class':'some_id'}),
            inp = $('<input />', {type:'text', id:'prop_name', 'class':'prop_name', placeholder:'Property name'}),
            anc = $('<a />',     {href:'#', 'class':'remover', text: 'Remove'});

        $('#variants').append(li.append(inp, anc));

        anc.on('click', function() {
            if ($('#variants > li').length < 3) $('#some_name').closest('li').hide();
            $(this).closest('.some_id').remove();
        });
    }
});

FIDDLE

Upvotes: 4

Related Questions