Jim Evans Jim Evans - 5 months ago 17
Javascript Question

jQuery issues in ASP.Net Master-Child page scenario

Having issues getting jQuery to work in this scenario:
Visual Studio 2010
.Net 4.0 Framework
jQuery 1.7.1 (also tried 1.4.1)

I created a default ASP.Net Web Application in VS2010 allowing the tool to create a Master Page and the basic child pages (Defallt, About, etc). I then create a new page to test the jQuery - a child page using the default Master page. I put some div's on the page and an HTML button and wired up the jQuery to change the background color of the div's when the button is clicked. It does change the color for about 1/10th of a second but then changes right back. I tried a few different things like making the div's disappear when the button is clicked - same result - disappears then comes right back. So I tried popping an alert (from jQuery code) when the button is clicked - this worked fine. It seems as though if I try to manipulate CSS there is an issue - otherwise things are fine. The page and site are extremely simple and basic. The HTML and script code for the page:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="jQuery.aspx.vb" Inherits="TestWeb.jQuery" %>




<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function () {
$("button").click(function () {
$("p").css("background-color", "red");
});
});

</script>





<h2>
jQuery Integration Testing
</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>




For some reason the content tags are not showing up when I past the code above so... The Script tags are contained within the
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
tag and the rest of the HTML is contained within the
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
tag

Answer

The button is submitting the page to the server, and so your background is changing then the page is getting refreshed back to the start. You need to add "return false" to the end of the click handler to cancel the navigation.

<script type="text/javascript">

    $(document).ready(function () {
        $("button").click(function () {
            $("p").css("background-color", "red"); 
            return false;
        });
    });

</script>
Comments