0

My code is as follows:

<script>

$(document).ready(function() {

    var tagCounter=0;

    $("#tag-add-button").click(function () {
      var text = $("#tagadd").val();
        $("#set-tags").append("<input type='text' id='tag"+tagCounter+"' READONLY>");
      $("#tag"+tagCounter).val(text);
        $("#tagadd").val("");
        tagCounter++;
    });


});
</script>

This does the following:

When tag-add-button is clicked, it takes the text from the inputbox (tagadd) and puts it in a new inputbox thats appended to the set-tags div. The tagadd inputbox is then made blank.

The problem I'm having, is I want each input box to have its own remove button. But I don't see how the javascript can be generated for that when there can be an unlimited number of input boxes...

Any ideas?

3 Answers 3

1

Put the input element inside of a div or span, and make the remove button a sibling of the input element. Then, in the onclick handler of the button, just do something like $(this).parent().remove()

This has the effect of removing both the input element, and the remove button itself

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

Comments

1

Rather than using an id (#tag-add-button), use classes and then use the each function of jQuery and traverse to the appropriate elements.

Comments

0
$(document).ready(function() {

    var tagCounter=0;

    $("#tag-add-button").click(function () {
        var text = $("#tagadd").val();
        $("#set-tags").append('<input type="text" id="tag'+tagCounter+'" READONLY /><span class="remove">Remove</span>');
        $("#tag"+tagCounter).val(text);
        $("#tagadd").val("");
        tagCounter++;
    });

    $('span.remove').bind('click',function(){
        $(this).prev('input').andSelf().remove();
    });


});

2 Comments

I'm trying this code, but nothing happens when I click "remove"
sorry replace 'bind' with 'live'

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.