Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Cloning and Update Button Icon

I feel like I am overlooking something really simple here. I need another set of eyes. I've spent much more time on this than I should.

Take a look at this fiddle => http://jsfiddle.net/R8SxU/

Why won't the Icon Update after adding more than one year? I want the top one to always be a plus to symbolize adding a new year, and the remaining ones below to be a minus to remove. It works on the first one, but only the first one. I believe I have the correct selector as the function (console out) is activated correctly with each button.

HTML

<div>
    <label for="year-0">Enter Year</label>
    <input id="year-0" type="number" title="Enter Year"/>
    <button id="addYear" title="Add Year">Year</button>
</div>

Jquery

$('#addYear')
    .button({icons: { primary: 'ui-icon-circle-plus' } })
    .on('click', function() { 
        var clone      = $('div').first().clone(true),
            peroid     = $('div').length;

        //update ID
        $(clone).find('label').prop('for','year-' + peroid);
        $(clone).find('input').prop('id','year-' + peroid);

        $('div:first button')
            .prop('id','')
            .attr('title','Remove Year')
            .addClass('removeYear');


        $(clone).insertBefore('div:first');
        $('.removeYear:first')
             .off('click')
             .button({ icons: { primary: 'ui-icon-circle-minus' } })  // Why Wont This Work
             .on('click', function() { console.log('remove function');  });

    });
like image 813
matchew Avatar asked Mar 08 '13 17:03

matchew


1 Answers

Try the following:

$('#addYear').button({
    icons: {
        primary: 'ui-icon-circle-plus'
    }
}).on('click', function () {
    var clone = $(this).parent().clone(),
        peroid = $('div').length;

    clone.find('label').prop('for', 'year-' + peroid).end()
         .find('input').prop('id', 'year-' + peroid).end()
         .find('button').prop('id', 'id' + peroid).prop('title', 'Remove Year')
         .addClass('removeYear').find('span:first').addClass('ui-icon-circle-minus');

    clone.insertAfter('div:last');
});

$(document).on('click', 'div:not(":first") button', function () {
    $(this).closest('div').remove();
});

http://jsfiddle.net/Y33GV/

like image 99
undefined Avatar answered Sep 25 '22 04:09

undefined