JcMey3r JcMey3r - 5 months ago 12
jQuery Question

javascript click not firing after partial view load

I have a view with a javascript section. In this view I have javascript with an onclick event which fires on a tab click to load a partial view this all works perfectly.

Now I know javascript on a partial view wont work properly so in the main view I want to add a click event for when a print button gets clicked.

<script type="text/javascript">
$(function () {

$('#printBtn').click(function () {
debugger;
printElement(document.getElementById("modal-body"));
window.print();
});

$('#tabStrip a').click(function (e) {
e.preventDefault()
var tabID = $(this).attr("href").substr(1);

$(".tab-pane").each(function () {
$(this).empty();
});

$("#" + tabID).empty().append("<div class='loader'><img src='/Content/img/Loader/ajax-loader.gif' alt='Loading' /></div>");

$.ajax({
url: "/Account/CustomerTab",
data: { Id: tabID },
cache: false,
type: "get",
dataType: "html",
success: function (result) {
$("#" + tabID).empty().append("<div id='replaceDiv'>" + result + "</div>");
$(document).trigger('ready');
debugger;
}
});
$(this).tab('show')
});
});
</script>


so the tab click works perfectly but once my partial view is loaded then the print button debugger doesn't get hit. this is the button in my partial view.

<button id="printBtn" type="button" class="btn btn-default">Print</button>

Answer

Try changing your clickhandler to something like this:

$(document).on('click','#printBtn', function() {
  //your code here
  }