Analytic Lunatic Analytic Lunatic - 4 years ago 683
Javascript Question

jQuery keyup event not working after partial view reload?

On my Index View, I have the below relevant jQuery code that executes when a user either hits Enter or clicks the Search Icon to trigger a Search:

<div class="homeContent">
@Html.Partial("~/Views/Shared/_homeIndexContent.cshtml")
</div>

@section Scripts {

<script type="text/javascript">
$(document).ready(function () {
// Set focus on load to the Search box.
document.getElementById("Search").focus();

$("#Search").keyup(function(event){
if(event.keyCode==13){
alert("Index.cshtml - Enter Pressed - Method inside Document.Reader().");
searchAssets();
}
});

// Called when user clicks the magnifying glass icon next to the Searchbox.
function searchAssets() {
alert("Index.cshtml - searchAssets() called.");
var searchValue = document.getElementById("Search").value;
$.ajax({
url: '@Url.Action("search", "Home")',
data: { searchCriteria: document.getElementById("Search").value },
success: function (resp) {
$(".homeContent").html(resp);
document.getElementById("Search").value = searchValue;
document.getElementById("Search").focus();
var rows = $('.grid-table tbody tr').length;
$('#rowCount').html(rows);
setVerifyBtnClass();
}
});
}


HomeController:

public ActionResult Search(string searchCriteria)
{
fillPagingIntervalList();
var SearchResults = db.TABLE.ToList().Where(m.Status.STATUS_DESCRIPTION != null && m.Status.STATUS_DESCRIPTION.ToString().ToUpper() == searchCriteria.ToUpper() || // Other search Code
// Return the "refreshed" partial view without reloading entire page.
return PartialView("~/Views/Shared/_homeIndexContent.cshtml", SearchResults);

}


Everything appears to work fine on the first search, but partial view has reloaded I can no longer perform a new Search by clicking the ENTER key.
I can still trigger a new search via the Search Icon being clicked, but why can I no longer use the Enter Key?

If I am just reloading the Partial View, I would think my jQuery inside the Document.Ready() should still be accessible?

Answer Source

but partial view has reloaded I can no longer perform a new Search by clicking the ENTER key

You should use event delegation .on() since the element with id Search will be added dynamically after the reload, simple keyup event can't deal with fresh DOM :

$("body").on("keyup", "#Search", function(event){
    if(event.keyCode==13){
        alert("Index.cshtml - Enter Pressed - Method inside Document.Reader().");
        searchAssets();
    }
});

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download