views:

32

answers:

2

With jQuery, in (document).ready I assigned a click function to all buttons of my asp.net (aspx) page. When I click a button outside , the function works properly. When clicking a button INSIDE the form, it doesn't work. Why?

Here my default.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuery._Default" %>

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

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            $("button").click(function () {
                $("input").before("ciao");
            });   
        });

    </script>
</head>
<body>

<button id="Button1">Button BEFORE Form</button>
<button id="Button2">Another BEFORE Form</button>

    <form id="form1" runat="server">


    <button id="btStart">Button in Form</button>
    <div>
    <input type="text" value="I like number 1" />
    <input type="text" value="Smile to number 2" />
    </div>
    </form>
</body>
</html>

I'm using Visual Studio 2010. I tried also with jQuery 1.4.2, same problem.

Thanks for letting me know, cheers.

+3  A: 

Since you are clicking a button in a <form>, it triggers a submit action. Try adding

return false;

after

$("input").before("ciao");

to prevent the default action related to that click event.

elusive
+1  A: 

It should work but the button is just submitting and refreshing so you are not noticing it. Since your using asp.net you could do it by just using an asp:Button like:

<asp:Button ID="yourButton"
    OnClientClick="$('input').before('ciao'); return false;" Text="Test" />
Kelsey