Elliot
Elliot

Reputation: 13835

Dynamic javascript using JQuery?

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?

Upvotes: 0

Views: 165

Answers (3)

Ian Wood
Ian Wood

Reputation: 6573

$(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();
    });


});

Upvotes: 0

Blair McMillan
Blair McMillan

Reputation: 5349

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

Upvotes: 1

Joel Martinez
Joel Martinez

Reputation: 47749

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

Upvotes: 1

Related Questions