ASP.net Button OnClick Validation - asp.net

I have an asp:button with an onclick property that posts back to the server. I would like to do some validation on the contents of a textbox before I fire the postback. I want to do the validation in javascript using some regex.
I cannot use an asp:XXXXvalidator; I just can't due to what my web app does.
Is there a way to call a javascript function from an asp:button that then calls the postback?
I know I can use OnClientClick to call js from the asp:button, but once I call the JS how do I signal that I want to postback the button?

Create a javascript function which returns true/false on your check. If you return false, then the page will not be submitted to the server.
Pseudo-code:
<script type="text/javascript">
function check()
{
if( valid ) return true;
return false;
}
</script>
<asp:Button ID="btnAdd" runat="server" OnClientClick="return check()" OnClick="click" />

Related

ASP.NET TextBox's OnTextChanged server event should fire some client code before going to server

My UserControl has a TextBox, that is subscribed to OnTextChanged event. However, since a lots of business logic and integrations happens on server, I want to disable a form while postback is being performed with some client-side javascript and I'm not sure how to achieve it the right way.
Can I solve this with ClientScriptManager.GetPostBackEventReference?
Edit: as my question seems to be misunderstood:
TextBox is subscribed to event OnTextChanged="tb_TextChanged" which will result on client in onchange=__doPostBack('tb') so I want to inject my javascript disableForm() to onchange DOM event. I know how to implement disableForm(), the question is how to inject my javascript properly?
I would suggest you use the javascript onblur event and check if the field value is changed. If so, you can use jQuery like the below to disable the form elements.
To disable a form element such as a text input or a button (with a made-up id: #elm):
$("#elm").attr("disabled", "disabled");
To enable a disabled form element:
$("#elm").removeAttr("disabled");
You should be able to do this with some simple JavaScript:
<script type="text/javascript">
disableFormFields = function(){
if (document.all || document.getElementById){
for (i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if (el){
el.disabled = true;
}
}
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server" onchange="disableFormFields();" OnTextChanged="TextBox1_TextChanged" />

validation in asp.net

i am using validators for validation and on linkbutton i am diaplaying popup.
my problem is i want to disable linkbutton means until page is validated means the popup should not be displayed till the page gets validated
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="addProduct-disable" Enabled ="false"
Text="Assign Filter Criteria" CausesValidation="true"></asp:LinkButton>
Try to validate client-side, if possible, via AJAX-Methods.
You may consider using the jQuery event.preventDefault() method.
$('[id$="LinkButton1"]').click(function(event) {
if(! valdiateYourPage() ) {
event.preventDefault();
// display validation errors or something
}
else {
//proceed as normal
}
});
Put your page validation logic in the valdiateYourPage() javascript method. If it valdiates, then process as normal, if not then preventDefault() will stop any further event execution by your LinkButton.

Mixing Asp.net default validation with a custum submit action

I have a page whose submit buttton does dot submit at all. It rathers has a some javascript in OnClientClick that employs some logic and redirects the user to a calculated URL. The thing is I want to use ASP.net default validation in this setup. I need to be able to query the state of the client side validation in the javascript. How do I do that?
This appears to be what your looking for, using ASP.NET Validation from client code
<asp:Button ID="btnAddEntry" runat="server" OnClientClick="ValidateAndAddNewEntry(); return false;" CausesValidation="true" ValidationGroup="AddEntry" Text="Create" />
JavaScript
function ValidateAndAddNewEntry() {
var res = Page_ClientValidate("AddEntry");
if ( res == true )
{
//Do work
}
}

LinkButton does not invoke on click()

Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger

How do I cancel a server control event in the client side?

I have an asp.net image button and I want to cancel the click event incase he fails the client side validation... how do I do that?
There is an OnClientClick event you can set this to your javascript function. If you return true it will continue to the post back. If you return false the post back will not happen.
<asp:Button ID="NavigateAway" runat="server" OnClientClick="javascript:return PromptToNavigateOff();" OnClick="NavigateAwayButton_Click" Text="Go Away" />
<script type="text/javascript">
function PromptToNavigateOff()
{
return confirm("Are you sure you want to continue and loose all your changes?");
}
</script>
<asp:ImageButton OnClientClick="return ValidatorOnSubmit()" />
The ValidatorOnSubmit() function should already be included by the ASP.NET framework if you have validators on your form. The standard WebForm onsubmit function looks like this:
function WebForm_OnSubmit() {
if ( typeof(ValidatorOnSubmit) == "function"
&& ValidatorOnSubmit() == false) return false;
return true;
}
I would simply reverse logic and not allow the user to click the button until he has filled the information. Put mandatory markers and if it is filled it then the button is enabled.

Resources