Reputation: 61
This doesn't work and I don't understand why, I have tried that code on W3schools and that works, I think the problem might be the reference or something, I'm new to ASP.NET.
ASP Code(Master Page)
<script src="./Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#bt_insertar").click(function () {
alert("Handler for .click() called.");
});
});
</script>
<asp:ContentPlaceHolder id="head" runat="server"></asp:ContentPlaceHolder>
Index.aspx
<td class="style4">
<asp:Button ID="bt_insertar" runat="server" Text="Insertar" Width="71px"
onclick="bt_insertar_Click" style="height: 26px" />
</td>
Upvotes: 3
Views: 16642
Reputation: 1073978
By default, the ID
you give your runat="server"
control isn't the id
that ends up on the DOM element. You can get the ID that ASP.Net generates from ClientID
property on the server-side control object. E.g., change:
$("#bt_insertar").click(...
to
$("#<%= bt_insertar.ClientID%>").click(...
...if that code is in a page ASP.Net parses (as opposed to an external JavaScript file).
As of ASP.Net 4, you can control this behavior via the ClientIDMode
property. For instance, if you use the Static
mode (control.ClientIDMode = CLientIDMode.Static;
), then the ID
is in fact passed through as-is. But the default value for ClientIDMode
is Predictable
, which modifies the ID
you use.
Upvotes: 5
Reputation: 13503
Several points:
src="../Scripts/jquery-1.4.1.js"
instead of src="./Scripts/jquery-1.4.1.js"
document.ready
event instead you can include OnClientClick="bt_insertar_Click();"
in your asp:Button
and then you can define your function bt_insertar_Click()
<script type="text/javascript">
function bt_insertar_Click() {
alert("Handler for .click() called.");
}
</script>
It is a better programming practice to use a separate .js file for you web page so you can move all the relevant js functions to this js file and then include it like you did with the jquery file.
Upvotes: 0
Reputation: 2788
To Bind jquery function to Asp.net Server control you have to write code this way.
<script type="text/javascript">
$(document).ready(function () {
$('#<%= bt_insertar.ClientID %>').click(function () {
alert("Handler for .click() called.");
});
});
Upvotes: 1