CaffeineShots
CaffeineShots

Reputation: 2162

dynamic add and delete input field jquery 1.10

Hi I'm having trouble with this fiddle I found somewhere it works perfectly on 1.4 jquery but I am using 1.10 version of Jquery.

I notice that live method is deprecated in 1.10 so I user on to replace live but still not doing as it supposed to do.

my toubled fiddle is here

I used to code back end so please spare me, could anyone help me with this?

Upvotes: 0

Views: 493

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

You should use parent selector $("#content") with on() and use prop() to make button disable like,

$("#content").on("click", ".plus",function(){
    var parent = $(this).closest(".iteration");// use closest
    parent.append('<input type="text" value="Create a task for this iteration" />');
    var nbinput = parent.find("input[type='text']").length;
    if(nbinput == 5)
        parent.find(".plus").prop("disabled",true);// use prop()
    if(nbinput > 0)
        parent.find(".moins").prop("disabled",false);
});
$("#content").on("click",".moins", function(){       
    var parent = $(this).closest(".iteration");// use closest
    parent.children("input").last().remove();
    var nbinput = parent.find("input[type='text']").length;
    if(nbinput < 5)
        parent.find(".plus").prop("disabled",false);// use prop()
    if(nbinput == 0)
        parent.find(".moins").prop("disabled",true);
});

Demo

Upvotes: 3

Richard Dalton
Richard Dalton

Reputation: 35793

To make on work like you wanted you need to specify an element that won't be changed as the main selector and pass the dynamic element selector as the second parameter:

$("#content").on("click", ".plus", function(){

Also, there was an error with the code that disabled the plus and minus buttons, instead of setting the disabled attribute to empty you want to remove it completely:

parent.find(".moins").removeAttr("disabled");

Finally, changed the .parent().parent().parent('.iteration') to

$(this).closest(".iteration");

As this is much simpler and less likely to be broken by changes to your html.

http://jsfiddle.net/infernalbadger/L3s3w/3/

Upvotes: 3

Related Questions