I have an asp.net app with an asp:button that causes a postback, this means that the html for the input has an onclick attribute that is auto generated, I need to add an event via jQuery to the onclick attribu开发者_StackOverflow社区te that fires before the auto generated postback is fired.
Below is an example of the html generated, i need to make sure that my event added by jQuery fires before the WebForm_DoPostBackWithOptions() function.
<input id="ctl00_MainContent_Save" type="submit" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$Save", "", true, "", "", false, false))" value="" name="ctl00$MainContent$Save">
for more clarity, I know I can add an event via jQuery like this:
$('#ctl00_MainContent_Save').click(function() {
somfunction();
});
but i want my event to fire before the WebForm_DoPostBackWithOptions
You can probably try mousedown event which will be fired before the click event is triggered.
$('#ctl00_MainContent_Save').mousedown(function() {
somfunction();
});
or try the below code
$(document).ready(function(){
$('#ctl00_MainContent_Save')
.attr("onclick", null)
.removeAttr("onclick")
.click(function() {
somfunction();
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($(this).attr("name"), "", true, "", "", false, false));
});
});
Hope this will give you an idea on how to do.
<asp:Button ID="bsrc" runat="server" Text="Search" OnClick="bsrc_Click" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#<%= bsrc.ClientID %>').click(function(e)
{
return true;
});
});
</script>
When you will click on button first it will call the javascript function and then will go for server side. If you want to stop calling server side event from javascript code just return false;
in place of return true;
How about:
<input id="ctl00_MainContent_Save" type="submit" value=""
name="ctl00$MainContent$Save">
...
$('#ctl00_MainContent_Save').click(function(e) {
e.preventDefault();
somfunction();
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions("ctl00$MainContent$Save",
"", true, "", "", false, false))"
});
If you can't alter the HTML, you could try (warning: untested!)
var $link = $('#ctl00_MainContent_Save');
var oldFunction = $link[0].onClick;
$link[0].onClick = null
$link.click(function(e) {
e.preventDefault();
somfunction();
oldFunction();
});
精彩评论