User931778073 posted
I am trying to inject HTML elements dynamically into an empty DIV element on my VB.net web form using jQuery when buttons are clicked. I made sure to clear the DIV before adding new contents to it.
The script works perfectly fine in a regular HTML file where I do not have to check for PostBacks. But on my Vb.net web form the added contents appear for less than a second before disappearing. I put the following code in Sub PageLoad to inform the frontend
whether PostBack occurs.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
ClientScript.RegisterHiddenField("isPostBack", "1")
End If
End Sub
Then I check for PostBacks in document ready function. My markup and script are below
<head>
<script src="jQueryCDN">
</script>
<script>
var content = "";
function addDiv1() {
//Empty DIV before adding new content
$('#container').empty();
content = "";
content = "<div>Test1</div>";
$('#container').append(content);
}
function addDiv2() {
$('#container').empty(); content = "";
content = "<div>Test2</div>";
$('#container').append(content);
}
$(document).ready(function(){
var isPostBackObject = document.getElementById('isPostBack');
if (isPostBackObject != null) {
//Call function to add DOM elements to DIV
$("#addDIV1").click(function () {
addDiv1();
});
$("#addDIV2").click(function () {
addDiv2();
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button id="addDIV1">Add DIV1</button>
<button id="addDIV2">Add DIV2</button>
<div id="container"></div>
</div>
</form>
</body>
Needless to say it is not working, the added contents still disappear. Please point out what I'm doing wrong.