0

Adding partial views dynamically into the main view on button click like the following , dynamically loaded views input failed to attach jQuery on main view but they this attachment work perfectly on partial views.

Main view

 <input type="button" name="BtnAddNew" value="Add New" onclick="AddCustomer();" />

    <script>
        function AddCustomer() {
            $.get("DataEntryScreen").done(function (r) {
                $('#DivDatEntry').html(r);
            });
        }

        $('#btnCancel').click(function (e) {//not work on main view
            alert();
            $('#DivDatEntry').html("");
        });

    </script>

Partial view=DataEntryScreen.cshtml

@{
    AjaxOptions o = new AjaxOptions();
    o.OnSuccess = "OnSaveSuccess";
}
@using (Ajax.BeginForm("SaveCustomer", "SPA", o))
{
    <table>
        <tr>
            <td>Customer Name:</td>
            <td><input type="text" name="CustomerName" value="" /></td>
        </tr>
        <tr>
            <td>Address:</td>
            <td><input type="text" name="Address" value="" /></td>
        </tr>
        <tr>
            <td>Age:</td>
            <td><input type="text" name="Age" value="" /></td>
        </tr>
        <tr>
            <td colspan="3" align="right">
                <input type="submit" name="name" value="Save" />
                <input type="button" name="name" value="Reset" />
                <input id="btnCancel" type="button" name="name" value="Cancel" />
            </td>
        </tr>
    </table>
}

Now dynamically loaded partial view="DataEntryScreen.cshtml" button="btnCancel" attach jQuery event on the main view is not work, then writing the same jQuery syntax on correspondent partial view work perfectly.

<script>


    $('#btnCancel').click(function (e) {//perfectly work on partial view.
        alert();
        $('#DivDatEntry').html("");
    });

</script>

Why jQuery event attachment not work on main view?

shamim
  • 6,640
  • 20
  • 85
  • 151
  • [event delegation](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)? – gaetanoM Jan 15 '19 at 13:41

2 Answers2

2

It does not work, because you are trying to attach event listener to element, which does not exist in DOM yet, at the time jQuery function is called.

Step-by-step explanation:

In main view, when the script tag is evaluated, the $('#btnCancel') function is called, which does not find #btnCancel element on the page - because it does not exist yet. This element is added to the page only after you fetch it asynchronously, when calling AddCustomer().

So, the $ function returns empty list [].

Because jQuery does not find anything, .click() function which is called afterwards are operating on empty list, and does not attach your event listener.

Why it works when you move code to the partial:

When you move the $('#btnCancel') function call to the partial view, the order of function calls changes. First, the partial needs to be fetched asynchronously, then the response is added to the DOM, then the script tag is evaluated, and finally the $('#btnCancel') function is called, which in turn finds element #btnCancel in the DOM and passes result to the .click() function, which attaches your event listener.

Possible solution:

It is possible to postpone creating new event listeners, until asynchronously fetched elements are added to the DOM.

To do so, you can modify AddCustomer function.

In main view:

function AddCustomer() {
  $.get("DataEntryScreen").done(function (r) {
    $('#DivDatEntry').html(r).find('#btnCancel').click(function (e) {
      alert();
      $('#DivDatEntry').html("");
    });
  });
}
Anastazy
  • 4,624
  • 2
  • 13
  • 22
  • Thanks for your valuable description, hope you extend your answer with guideline how to add event handlers to dynamically created elements? – shamim Jan 15 '19 at 14:58
1

Normally i fix this problem by using event delegation in the main view:

<script>
    $('body').on('click', '#btnCancel', function (e) {
        alert();
        $('#DivDatEntry').html("");
    });
</script>
Mustapha Larhrouch
  • 3,373
  • 3
  • 14
  • 28
  • Since the button, is loaded dynamically after the view load you tie the click event to the body but I want to tie this event with another element like my main view div or table then why it does not work. – shamim Jan 15 '19 at 14:42