最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop form submission when an html button with onserverclick enabled is clicked in an asp.net web App - Stack Overfl

programmeradmin0浏览0评论

I have a button in an asp application which submits a form.

    <input type="submit" id="sumbit" value="Sign up" runat="server" 
     onserverclick="sumbit_ServerClick2" class="submitbutton"/>

I have a javascript function which returns true and false. How do i prevent the form from being submitted if the javascript function returns false. I cant access the form tag as i am using masterpage and the whole contentplacedholder is enclosed within a runat="server" form.

I have a button in an asp application which submits a form.

    <input type="submit" id="sumbit" value="Sign up" runat="server" 
     onserverclick="sumbit_ServerClick2" class="submitbutton"/>

I have a javascript function which returns true and false. How do i prevent the form from being submitted if the javascript function returns false. I cant access the form tag as i am using masterpage and the whole contentplacedholder is enclosed within a runat="server" form.

Share Improve this question asked May 12, 2013 at 21:41 thunderbirdthunderbird 2,7335 gold badges29 silver badges53 bronze badges 1
  • 1 Is the javascript doing some type of validation? if so look into the validation controls to prevent postback. – fnostro Commented May 12, 2013 at 21:46
Add a ment  | 

3 Answers 3

Reset to default 5

Use the onclick attribute to test the return value of your JS function:

<input type="submit" id="sumbit" value="Sign up" runat="server" 
     onserverclick="sumbit_ServerClick2" class="submitbutton" 
     onclick="if (!yourFunction()) return false;" />

Assuming your function is called yourJsFunction, I think you can just use onclick="return !!yourJsFunction();" on the input element, like this:

<input type="submit" id="sumbit" value="Sign up" runat="server" onclick="return !!yourJsFunction();"
 onserverclick="sumbit_ServerClick2" class="submitbutton"/>

Use !! in front of the function call to force a boolean value.

--

For ASP.NET Button use onClientClick="return !!yourJsFunction();".

Read more here.

Set the button type to "button" (defaults to submit), this will disable the submit of the form and rely upon the __doPostBack() to handle the wiring up.

<button id="MyButton" runat="server" type="button" onserverclick="MyButton_Click">Submit</button>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论