Reputation: 218
I want to show and hide my partial view when the same button is clicked. The below code work for showing the partial view. How do I remove the partial view if the user click the same button again?
<div id="myPartialView"></div>
$('#myBtn').click(function() {
$.ajax({
url: '/Home/GetData',
datatype: "html",
type: "GET",
cache: false,
success: function(result) {
$('#myPartialView').empty();
$('#myPartialView').html(result)
},
error: function(xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('error - ' + errorMessage);
}
});
return false;
});
Upvotes: 1
Views: 1435
Reputation: 5757
I'm caching myPartialView
to a variable so we just have to look for it once.
EDIT:
Changed the code to test for :empty
, so it should work even in the initial state.
$('#myBtn').click(function () {
var $myPartialView = $('#myPartialView');
if ($myPartialView.is(':empty')) {
$.ajax({
url: '/Home/GetData',
datatype: "html",
type: "GET",
cache: false,
success: function (result) {
$myPartialView.html(result);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('error - ' + errorMessage);
}
});
}
else {
$myPartialView.empty();
}
return false;
});
Upvotes: 2