I just found a funny behaviour in asp.net.
I have a form that has got a fieldset which is hidden when initially loaded and a submit button.
What I’m expecting to do is that when a user clicks the submit button, the fieldset would appear. The thing is, when I try to click the submit button, it will show the fieldset element but would dissaper immediately.
Would it be possible if you could point me in the right direction as to where in my code am I doing something wrong? See my code below.
Thanks a million!
Cheers,
Ann
<%@ Page Language="C#" AutoEventWireup="true" Inherits="JavascriptTest._Default" %>
<!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>Test Javascript</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
}
</script>
<script type="text/javascript">
$(document).ready(function () {
var btnSubmit = '#<%= btnSubmit.ClientID %>';
$('#result').hide();
$(btnSubmit).click(function () {
$('#result').show();
return true;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset id="result">
<legend>Search Result</legend>
<p>Cras risus. Parturient lectus! Ac quis. Enim arcu adipiscing nunc? Porta magna ultrices elit amet, turpis vel nunc, massa pulvinar sit, pulvinar amet elementum tristique diam parturient, eu in dolor, non pulvinar nisi, penatibus? Velit tincidunt? Pulvinar nec urna ac, pulvinar purus integer phasellus, ridiculus non dictumst penatibus dolor rhoncus elementum pellentesque? Adipiscing et, dapibus, amet ac porta! Magna tristique, sed porta elit mid. Et ultricies et elit mattis. Arcu! Elementum ac? Nisi turpis, vel in massa pellentesque porta lectus, egestas aenean scelerisque risus? Placerat purus cum et. Egestas sociis, adipiscing porttitor scelerisque integer? Auctor a arcu sit aliquam amet sed odio, velit turpis, risus, porttitor mid diam, ac arcu lectus auctor, facilisis tincidunt! Et, proin, turpis nunc velit? Elementum.</p>
</fieldset>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
The default button behavior is kicking in here, causing the
<form>to submit and your page to refresh (hiding the<fieldset>again). You need to prevent that default behavior withevent.preventDefault()orreturn false, like this:event.preventDefault()will just prevent the submission where asreturn falsewill kill the event dead in its tracks…so I really considerreturn falseoverkill here. It’s really better to do what you’re trying to do, not more than that which can cause potential unwanted issues later (for example a.live()/.delegate()handler wouldn’t work if you killed the event, etc).