How to run the client side script on textchange event of textbox? - asp.net

Suppose You have TextBox Control and the user enter any key into it. When the user enter the key ,on that event the key which is pressed stored into array and show him any another character.
Example . suppose i enter "x" but the textbox should display me "p".

Sounds like you need some JavaScript! With this code no matter what key the user presses, the textbox will type out ‘p.’ You could mix in a random letter generator if you really want to get crazy.
<script type="text/javascript">
function ScrewyKeypad(evt) {
var info = document.getElementById('<%= TextBox2.ClientID %>').value;
document.getElementById('<%= TextBox2.ClientID %>').value = info + 'p'
return false;
}
<asp:TextBox ID="TextBox2" runat="server" onkeypress="return ScrewyKeypad(event)" ></asp:TextBox>
And be sure to register the script in your page load event:
if (!IsPostBack)
{
TextBox2.Attributes.Add("onkeypress", "return ScrewyKeypad(event)");
}

Related

Control in UpdatePanel not found using $find

I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function

Pass value from javascript function in client side to server side in asp.net

The web form has grid view which contains Delete link. On clicking the link, confirmation message should be displayed. I am using function which displays the confirmation dialog box. On clicking OK button, the respective record should be deleted. How can I pass some value on clicking OK button in the dialog box to perform delete operation?
void ConfirmMsg(string cMsg)
{
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
String cstext = "confirm('" + cMsg + "');";
cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}
just use this line in place of ur delete button.nothing needed:
<asp:LinkButton ID="lbDelete" runat="server" OnClientClick="return confirm('Are you sure want to delete the Company Information?')" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
use a link button as Delete link and
OnClick = your delete function
OnClientClick = return Confirm("Confirmation message")
if user clicks OK, the function in OnClick will execute. Otherwise it will not

CustomValidator using CustomValidationScript

I have an ASP.NET TextBox with a CustomValidation control that invokes client side validation script.
<asp:TextBox ID="txtSubsContrRbtAmt" runat="server"
CssClass="textEntry NumericInput" Width="150px"
Text="" onKeyUp="SumValues();" MaxLength="16"></asp:TextBox>
<asp:CustomValidator ID="cvalSubsContrRbtAmt" runat="server" ClientValidationFunction="ValidatetxtSubsContrRbtAmt"
ControlToValidate="txtSubsContrRbtAmt" CssClass="errlable" ErrorMessage="Max Decimals = 7"
SetFocusOnError="True" ValidationGroup="CarbsAdd"></asp:CustomValidator>
Here's the Client script:
function ValidatetxtSubsContrRbtAmt(source, args) {
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var amount = txtSubsContrRbtAmt.value;
args.IsValid = ValidAmount(amount);
if (!args.IsValid)
txtSubsContrRbtAmt.focus();
}
function ValidAmount(amount) {
if (isNumber(amount)) {
return (RoundToXDecimalPlaces(amount, 7) == amount);
}
else {
return true;
}
In the ValidatetxtSubsContrRbtAmt function, the "source" parameter is the CustomValidator. That control has a property "ControlToValidate." If I can get to it, I can programmatically retrieve the value from that control and not have to have a separate function to validate each textbox.
jQuery is too much for me at this point, I'm looking for a plain old Javascript approach, please.
You don't have to get the text box. You can get the value from args.Value. The focus should be set automatically if you set SetFocusOnError="true".
function ValidatetxtSubsContrRbtAmt(source, args) {
var amount = args.Value;
args.IsValid = ValidAmount(amount);
}
You should be able to get to the control from the source object.
function ValidatetxtSubsContrRbtAmt(source, args) {
var controlToFocusOn = source.ControlToValidate;
you can switch that out with "document.getElementByID()" to get the ID or whatever attribute you need
var controlId = document.getElementById(source.ControlToValidate).id;
}
now you can focus or do what you need with the control. I had to access the the actual ControlToValidate earlier today from a CustomValidator.

Before deleting a row in repeater , i want to do validation asking that, are sure you want to delete..?How can i do this?

i want to do validation asking that, are sure you want to delete..?
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>' OnCommand="Calling_Delete">Delete</asp:LinkButton>
The easiest way to do it is to use Confirm Button extender. Just drag this control next to the linkbutton and set the Confirmbutton externders TargetControlID to the Id of the Linkbutton. Everything else will be taken care of by the control.
More info- http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
Use OnClientClick property to attach the java-script that will do the prompting. For example,
<asp:LinkButton ID="lnkDelete" runat="server"
CommandName='<%# DataBinder.Eval(Container.DataItem, "ImageId") %>'
OnClientClick="return confirm('Are sure you want to delete..?');"
OnCommand="Calling_Delete">Delete</asp:LinkButton>
This answer has one way to do it, using jQuery and a jQuery UI dialog
One advantage of using a javascript dialog such as that provided by jQuery UI is that the popup dialog is modal only for the web page on which it is displayed. You can still access other tabs within your browser while the popup is displayed.
Other solutions that use the javascript confirm function will force the user to dismiss the confirmation dialog before switching to another browser tab.
if u'd like to use custom confirmation ( like jquery dialog,bootboxjs etc.. ) then you have to generate button's "postback string" or get it somehow. asp.net gives such as postback name after rendering the page; __doPostBack('ctl00$ContentPlaceHolder1$btnDeleteSelected',''). after realizing this i wrote a js function which is generates button's postback str;
function PostBackBtnMake(id) { // id : ContentPlaceHolder1_btnDeleteSelected
var result;
var temp = id.split('_');
result = 'ctl00$' + temp[0] + '$' + temp[1];
return result;
}
then i be able to use in custom confirmation box (in this case i used bootboxjs);
function PostBackBtn(e) {
var _result = false;
bootbox.confirm("Are you sure?", function (result) {
if (result) {
__doPostBack(PostBackBtnMake(e.id), '')
}
});
return _result;
}
it's worked for me, i hope it helps you too.

c# Validation for login

My script isnt checking the requirement can u help me out with this?
I'm trying to make it run the script before it run the onclick to check if login is right.
<script type="text/javascript">
function checkform() {
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
if(name.charAt(0)!='s'){
document.getElementById("divMessage").innerHTML = "Please insert an S infront";
return false;
if(pw.length< 8 && pw.length>16){
document.getElementById("divMessage").innerHTML = "Please key in a longer password";
return false;
}
}else{
return true;
}
</script>
<asp:Button ID="btnLogin" class="button" runat="server" CommandName="Login"
OnClientClick ="return checkform()" onclick="btnLogin_Click" text="Login" />
You are trying to grab the controls based on tagNames. This way it could also return you a collection of controls as it says "document.get Elements ByTagName" Elements is plural. If your controls which you are trying to grab: UserName & Password are the actual ID in the Server controls use the following code:
<script type="text/javascript">
function checkform() {
var name = document.getElementById("<%=UserName.ClientID %>");
var pw = document.getElementById("<%=Password.ClientID %>");
if(name.charAt(0)!='s'){
document.getElementById("divMessage").innerHTML = "Please insert an S infront";
return false;
if(pw.length< 8 && pw.length>16){
document.getElementById("divMessage").innerHTML = "Please key in a longer password";
return false;
}
}else{
return true;
}
</script>
<asp:Button ID="btnLogin" class="button" runat="server" CommandName="Login"
OnClientClick ="return checkform()" onclick="btnLogin_Click" text="Login" />
In the case of the UserName & Password are not server controls by which I mean an asp control but rather its run on the client, for example its not a <asp:TextBox....
BUT a <input ... (which runs on the client) you could specify its id tag with the value of UserName and Password for the other one, with one change replace:
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
With:
var name = document.getElementById("UserName");
var pw = document.getElementById("Password");
Alternatively if you are trying to get it based on tagNames then you have to go thru the returned collection and find out which one is the control you want. For example if there is only one control with that name it will be the only item in the collection starting at 0 and if you go higher like 1 its out of range.
Hope this has been helpful to you.
When asp.net controls are rendered they have different id may be following are generating error
var name = document.getElementsByTagName("UserName");
var pw = document.getElementsByTagName("Password");
Set the ClientIDMode of the controls to Static.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
this way the client ids will be the same as the server ones.
Once you have done that, change your js script to use getElementById();
Hope it helps.

Resources