Inspite of calling asp.net button click event by jquery why my page refreshed.

Posted by Rashedbin under ASP.NET on 5/17/2015 | Points: 10 | Views : 518 | Status : [Member] | Replies : 1
Hi ! I am new in jquery and web programming.
simply my concept is when i click an asp.net
button then its run on server and page refreshed.
so we use jquery to run asp.net control on client side.

for this i write this following code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {

var a = $("#TextBox1").val();
if (a > 5)
$("#mydiv").text(a + ' is greater then 5')
});

});


</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<div id="mydiv"></div>
</div>
</form>
</body>
</html>


it's work fine. but the message which generated by this code"$("#mydiv").text(a + ' is greater then 5')"
is not remaining in page.because page is refreshed.

my quesion is inspite of calling button click by
jquery why my page refreshed and message is not remaining in page.

thanks all.




Responses

Posted by: Sheonarayan on: 5/17/2015 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Hi,

You are wrong in understanding how jQuery works and what is the function of jQuery. Of course jQuery works in the client side but it is not used to run asp.net code in the client side. ASP.NET code always runs on the server.

In this case, your button is asp.net button that gets converted into input type="submit" and when you attach a click event with jQuery on this button, it submits the page on the server.

As you just want to display message in the div at the client side on click of a button so simply replace the asp:Button with following

<input type="button" id="Button1" value="Button" />

Notice that type="button", it is NOT type="submit". So clicking on this button would not submit the page on the server.

So when you attach a click event, it doesn't submit the page on the server but simply writes the message in div.

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Rashedbin, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response