Mr. A
Mr. A

Reputation: 714

How to call button in Partial View from jQuery script (MVC)

I'm writing application who has few forms. In main view I have for example:

<h2>Index</h2>
<button id="bt1">Click from main view</button>

<div id="partial">

</div>

and then i call btn1 from script:

$("#bt1").click(function () {
        alert("btn1click");
    });

and also render the partial view:

$("#partial").load("/Home/Home");

and then call the second button:

Partial view:

<h4>Partial view</h4>
<button id="btn2">Click from partial view</button>

Script:

 $("#btn2").click(function () {
        alert("btn2click");
    });

but this action do nothing. I have no idea why. Can you help me? How can I call the button from script? I'm using ASP.NET MVC but for some reasons I can't use RenderPartial method.

Upvotes: 1

Views: 1224

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

Use event delegation like

$(document).on('click', '#btn2', function () {
        alert("btn2click");
    });

Basically, regardless of when #btn2 is loaded, this event should fire because it was delegated from the document. This is saying for all current and future #btn2 elements, execute this click handler

Upvotes: 2

Related Questions