I have created an application in ASP.NET and using JavaScript to validate the fields either its empty or not; calling that validation function onClientClick event of ASP.NET Button Control and also using onClick event for server side processing.
Here I am enclosing the javascript: validation function
function validate() {
if (document.getElementById("<%=txt_msn.ClientID%>").value == "") {
alert("Membership number can not be blank; Fill all fields marked as *");
document.getElementById("<%=txt_msn.ClientID%>").focus();
return false;
}
return true;
}
Here I am calling that function under ASP.NET Control
<asp:Button ID="btn_save_pi" runat="server"
Text="Save" OnClientClick="return validate()" OnClick="btn_save_pi_click" />
Now what I have observed that as the validation function returns false it executes the server side method i.e onclick event but on the return of true it do nothing. But when I switch the return value, means on empty field return true and on non empty field return false, then it works fine.
I am confuse in this why it is acting like that. It suppose to act like I have written above i.e. do nothing on false return and on true return execute server side processing.
Please explain this, it will help me to develop the further applications too.
Your code works perfectly fine for me in IE as well as FF.
So if it still gives you problem you can go for a approach with less problems using asp.net validation controls.
But if you still want to go for javascript validations of your own, use this:
http://docs.jquery.com/Plugins/Validation
You can go fancy with validation and make validations the way you want.
to understand it better, please go through the example given at the end or refer this:
http://jquery.bassistance.de/validate/demo/
Hope this helps....
So perhaps there is an actual solution, but I just do this little workaround to avoid the OnClientClick property altogether.
Hide your button:
style="display:none;"
Next to your button, stick in another "fake" button:
<input type="button" value="Save"
onclick="if (validate()) {
document.getElementById('<%=btn_save_pi.ClientID%>').click(); }" />
Related
I have a RadPanelBar as such...
<telerik:RadPanelBar
ID="ResourcesSubMenuRadPanelBar1"
Width="195px"
OnItemClick="RadPanelItemClick"
ExpandMode="MultipleExpandedItems"
OnClientItemClicked="RadPanelClientItemClicked"
OnClientLoad="RadPanelBarClientLoad"
runat="server"
AppendDataBoundItems="true"
EnableEmbeddedSkins="false"
OnClientItemCollapse="RadPanelClientItemClicked"
OnClientItemExpand="RadPanelClientItemClicked">
</telerik:RadPanelBar>
This all works as expected, except for one little thing. In the code behind, I explicitly set the NavigateUrl property to string.Empty but when an item is clicked, it adds a hash to the url. Obviously, this is because the href attribute has been set to "#" when the control renders the HTML.
I know that I can simply return false from the OnClientItemClicked event, but that will stop the ItemClick event from being fired on the server.
As I say, there is no real error with this code it's just bugging me (and, more importantly, the end users) that there is a # added to the URL.
Does anyone know how to stop this happening?
Try this in your OnClientItemClicking event:
eventArgs.set_cancel(true);
Ref: http://www.telerik.com/help/aspnet-ajax/panelbar-onclientitemclicking.html
And, if in case you want the post back to happen, I suppose there is a item.PostBack property (server-side). Set it to true. It should post you back - if the NavigateUrl is empty (or #).
Compatible in just about every browser, IE9 and up:
Javascript (no jQuery):
stripTelerikHashtag = function () {
[].forEach.call(
document.querySelectorAll(".rpLink"),
function (a) { a.removeAttribute("href") }
);
};
Javascript (with jQuery):
stripTelerikHashtag = function () { $(".rpLink").removeAttr("href"); };
In your ASP, set OnClientLoad on the RadPanelBar to stripTelerikHashtag.
I wanted to write javascript code on "OnClientClick" of the asp.net button and also I want the asp.net validation to be run for that button. but when i mix these both validation is not working. please help me out. Below is my code
ASPX
<asp:Button ID="btnAddToFeatureOffers" runat="server" Text="Add to Feature Offers"
OnClick="btnAddToFeatureOffers_Click" ValidationGroup="vgAddOffer" OnClientClick="add();" />
javascript
function add() {
var selectedOrder = $('#ctl00_MainContent_ddlFeaturedHostingType option:selected')[0].index;
var offer = $('#<%=txtOrder.ClientID%>').val();
var a = $("<a>").attr("href", "#").addClass("offer").text("X");
$("<div>").text(offer).append(a).appendTo($('#resultTable #resultRow td')[selectedOrder - 1]);
}
Try giving a return false or return true inside the function add based on your validation result.
Also no need to write selector like this
$('#resultTable #resultRow td')
Simply write
$('#resultRow td')
I need to run some script by onclick() of some , checkbox particularly, to decide should i invoke WebForm_doPostBack() or not.
If I will submit form in myScript() myself, it will not cause validation of another asp.net validators, so I really need a native WebForm_doPostBack() call.
Should I handle a submit form event or are there any more "asp.net" ways to do it?
CustomValidators don't work with checkboxes:).
Just to ensure your assumptions that custom validators do not work with checkboxes is not the ONLY reason for wanting to handle the checkbox click seperately, here is some code that will validate checkboxes using ASP.NET custom validators.
Custom Validators have a ClientValidationFunction property that is called automatically when the __doPostback is called or the form is submitted.
//The Script
function validateCheckBox(source, arguments)
{
if(!source.checked) arguments.IsValid = false;//set IsValid property to false
}
//The Validator
<asp:CustomValidator ID="validateCheckbox" runat="server" ControlToValidate="CheckBox1" ErrorMessage="You REALLY need to check this!" Display="Static" ClientValidationFunction="validateCheckBox"/>
Don't you try simply putting your own validation at submit button like that :
btnSubmit.Attributes["onclick"] += "return myValidation();";
<script>
function myValidation()
{
// if you do not want to postback just return false...
return true;
}
</script>
EDIT : You can use Page_ValidationActive to programmatically enable / disable the client side validation of your page.
Page_ValidationActive A Boolean
value that indicates whether
validation should take place. Set this
variable to false to turn off
client-side validation
programmatically.
I've got a checkbox that's set up as below:
<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="showLoadingScreen(this.checked);" AutoPostBack="true" Text="Check me for more data!" />
The function showLoadingScreen is as below:
function showLoadingScreen(isChecked) {
if (isChecked)
{
document.getElementById('form1').style.display='none';
document.getElementById('img_loading').style.display='block';
}
else { return false; }
}
I've added the else clause in hopes that I can get it to only post back when the checkbox is checked, but it's posting back in either case.
I've got a grid on the page (inside form1) that has a set of data loaded into it on page load, but in order to add some extra data to it I've added this checkbox (its a longer running process, so I only want to load it on demand, not upfront). When it's checked I want to show the loading gif, postback, grab the data, and return. If the box gets unchecked I don't want to do anything, since leaving more than enough data on the page is perfectly fine (that is to say, the data displayed upfront is a subset of the data displayed when the checkbox is checked).
Is there any way to make it so the checkbox auto posts back on checked, but not on unchecked?
Edit: Using Dark Falcon's suggestion, I've modified the checkbox to look like:
<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="return showLoadingScreen(this.checked);" AutoPostBack="true" Text="Include HQ Values" />
And the javascript to be:
function showLoadingScreen(checked) {
alert(checked);
if (checked)
{
document.getElementById('form1').style.display='none';
document.getElementById('img_loading').style.display='block';
document.form1.submit(); //my own addition, to get it to post back
}
else { return false; }
}
Now, it posts back on checked, but the box is not able to be unchecked anymore. As you can see I've added an alert to show the value being passed in. It's passing in the correct value when you uncheck the box (false), but then it somehow gets checked again.
It's not a huge issue, since there's really no reason to ever uncheck the box (since as I stated before, the dataset when checked is a superset of the unchecked dataset), but I'd still like to know why it's doing that. Any ideas?
Do not set AutoPostBack in this case. "AutoPostBack" means post back to the server any time the value of this control changes... which is NOT what you want.
Instead, use GetPostBackEventReference(myCheckbox,"") to get the appropriate postback script and call this from your showLoadingScreen method if the checkbox is checked.
For your onclick handler, you need to do:
return showLoadingScreen(this.checked);
Try to avoid using _doPostback as it is a hack which you will have to know what control ID is posting back and other parameters for that Javascript function from Microsoft ASP.NET. To understand what's happening behind the scene, you have to know why there is a postback and how to prevent the postback from happening.
Here's what's happening with an ASP.NET checkbox (ASP:Checkbox) when auto-postback is set:
<ASP:Checkbox runat="server" id="chkCheckbox" AutoPostback="true" onclick="return isDoPostback(this.checked);" ClientIdMode="static" ... />
generated HTML code is:
<input type="checkbox" ... id="..." onclick="return isDoPostback(this.checked);_doPostback(...);" .../>
The custom onclick event is appended to the beginning of the onclick event of the checkbox. No matter what you do, that prepended function call will execute. Worst off, if you have a return value, the _doPostback will never get executed.
This is what you really want to do (I use a mix of jQuery and native Javascript here):
var checkbox = $("#chkCheckbox");
...
checkbox .on("change", function(e)
{ if(this.checked)
{
var isConfirmedToContinue = confirm("Continue with Postback?");
if(!isConfirmedToContinue)
{ this.checked = false; //Uncheck the checkbox since the user canceled out
var onClickDelegate = this.onclick;
if(onClickDelegate)
{ var me = this;
this.removeEventListener("click", onClickDelegate); //Remove the onclick event so that auto-postback no longer happens
setTimeout(function()
{ //Add back the onclick delegate after 250ms
me.addEventListener("click", onClickDelegate);
}, 250);
this.onclick = null; //Remove the current onclick event by nulling it out
}
}
}
});
Try using a JS routine for checking whether it is checked, and if it is set to true, try doing:
_doPostBack(checkElementReference.name, "");
_doPostBack is responsible for performing posts to the server for controls that don't normally postback. You have to pass the name of the element, which on the server happens to be the UniqueID property for the server-side checkbox control.
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
}
}