The asp.net server control button first executes js and then the background method, asp. netbutton
With regard to the button Server Control, I have always wanted to reduce it by submitting data to the server. Those checks can be implemented on the client.
This requires javascript, but I found that javascript alone is not enough. The click event of the button Server Control is called "onClick ",
Therefore, javascript cannot use this event. Because the name is duplicated. What I want to achieve is to execute the javascript code of the client first when clicking the button, and then execute the background event.
If the html control is used, this problem does not exist. However, I want to implement this function of the server control, and sometimes the server control is also very useful.
Add a server control button to the aspx page
?
During page initialization, add a client event to the button Server Control. That is, add a code in the Page_Load () method:
?
12345 |
if (!IsPostBack) { // Add client events to button1 btnSave.Attributes.Add( "OnClick" , "return UserAddVerify()" ); } |
UserAddVerify is a function implemented on the js end. It is mainly used to check the data validity.
?
1234567891011121314151617181920212223242526272829303132333435363738 |
function UserAddVerify() { var userName = document.getElementById( "TxtUserName" ).value; var password = document.getElementById( "TxtUserPassword" ).value; var repassword = document.getElementById( "TxtUserPasswordConfirm" ).value; var identity = document.getElementById( "TxtUserIdentity" ).value; var mobile = document.getElementById( "TxtUserMobile" ).value; var realName = document.getElementById( "TxtUserRealName" ).value; var btnSave = document.getElementById( "btnSave" ); var identityReg = /(^\d{ 15 }$)|(^\d{ 18 }$)|(^\d{ 17 }(\d|X|x)$)/; var mobileReg = / 1 [ 3 - 8 ]+\d{ 9 }/; if (userName == "" || userName == null ) { alert( "User name cannot be blank" ); return false ; } else if (password == "" || password == null ) { alert( "The password cannot be blank" ); return false ; } else if (repassword == "" || repassword == null || repassword != password) { alert( "Sorry, the two passwords are different" ); return false ; } else if (identity == "" || identity == null || identityReg.test(identity) === false ) { alert( "Enter a valid ID card number" ); return false ; } else if (mobile == "" || mobile == null || mobileReg.test(mobile) == false ) { alert( "Enter a valid mobile phone number" ); return false ; } else if (realName == "" || realName == null ) { alert( "Name cannot be blank" ); return false ; } return true ; } |
The above return true and false are very important, which determines whether to execute the data. The next execution should be to submit the data to the background to process the data. When true is returned, the background executes the button#click method (event ).