简体   繁体   中英

How to remove textbox which created on run using jquery

I create link button, if it clicked, it will add textboxes with a delete link automatically. The problem is after textboxes and a delete link is added, when a delete link is clicked, it cannot delete the textbox. How to solve this?

View

@using (Html.BeginForm())
{
    <div id="editorRows">
        @foreach (var item in Model)
        {
            Html.RenderPartial("GiftEditorRow", item);
        }
    </div>
    @Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" })
    <input type="submit" value="Finished" />
}

@section Scripts {
    <script>
        $(document).ready(function () {
            $("#addItem").click(function () {
                $.ajax({
                    url: this.href,
                    cache: false,
                    success: function (html) {
                        $("#editorRows").append(html);
                    }
                });
                return false;
            });

            $("a.deleteRow").on("click", function () {
                $(this).parents("div.editorRow:first").remove();
                return false;
            });
        });
    </script>
}

Partial View for adding textboxes dynamically:

@model MvcApplication1.Models.Gift
@using MvcApplication1.Helpers

<div class="editorRow">
    @using (Html.BeginCollectionItem("gifts"))
    {
        <p>
            Item: @Html.TextBoxFor(x => x.Name)
            Value: @Html.TextBoxFor(x => x.Price, new { size = 4 })
            <a href="#" class="deleteRow">delete</a>
        </p>
    }
</div>

replace

$("a.deleteRow").on("click", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});

with

$(document).on("click","a.deleteRow", function () {
$(this).parents("div.editorRow:first").remove();
return false;
});

Since you are generating HTML dynamically with jquery you have to use event delegation .

Instead of

$("a.deleteRow").on("click", function () {
   $(this).parents("div.editorRow:first").remove();
   return false;
});

Try

$(document).on("click", "a.deleteRow" ,function () {
   $(this).parents("div.editorRow:first").remove();
   return false;
});

Read More Here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM