4
        $(function(){
            var namecounter = 0
            $("#getitem").click(function(){
                namecounter++
                var txtval = $("#txt").val();
                $('<tr><td><input type="button" name="txt'+ namecounter +'" value="remove" /><input type="text" id="txt'+ namecounter +'a" name="txt'+ namecounter +'a" value="'+txtval+'"/></td><td></td><td></td></tr>').appendTo('#pasok');
            });
            $(":button[name^='txt']").click(function(){
                var currentValue = $(this);
                var target = $("#" + currentValue.attr("id") + "a");
                $(target).remove();
            });
        });

How to delete created element via JQUERY?

2 Answers 2

2

Your button doesn't have an id attribute, it has a name attribute (both of which are also a directly accessible DOM properties), so you can do this:

$(function(){
    var namecounter = 0
    $("#getitem").click(function(){
        namecounter++
        var txtval = $("#txt").val();
        $('<tr><td><input type="button" name="txt'+ namecounter +'" value="remove" /><input type="text" id="txt'+ namecounter +'a" name="txt'+ namecounter +'a" value="'+txtval+'"/></td><td></td><td></td></tr>').appendTo('#pasok');
    });
    $("#pasok").delegate(":button[name^='txt']", "click", function(){
        $("#" + this.name + "a").remove();
    });
});

You can test it out here.

Also note the use of .delegate() so it works on the buttons you're adding, not just the ones that were there when your document.ready function ran.

Sign up to request clarification or add additional context in comments.

1 Comment

You probably need a space before the a though. "a"" a"
1

your target variable is already a jquery object. So you should change $(target).remove(); to target.remove();

1 Comment

That’s a good optimization, but sadly that can’t be the reason why his code breaks. Stuff like $($($($($('body'))))) still works; it’s just REALLY bad for performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.