I have to create a textbox which will ignore all the non numeric input.
I tried to use this code which I found in this site
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = Not Char.IsDigit(e.Keychar)
End Sub
But I have a mistake in this part of the code System.Windows.Forms.KeyPressEventArgs
What am I doing wrong?
hope this helps
Sub btnDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
if e.KeyChar= Chr(8)
'do something for backspace
else if e.KeyChar=(CHr(13)
'do something for enter
end if
end sub
I agree with Dai
Key stroke in ASP.net SHOULD ALWAYS be managed on the client side to avoid unecessary postback an avoid overloading server .
If you are not familiar with Javascript you can refer to this excelleent tutorial from W3School to manage the onChangeEvent of an input
http://www.w3schools.com/jsref/event_onchange.asp
If you really want to manage the key 'on fly', you can manage the 'onkeyDown' event
http://www.w3schools.com/jsref/event_onkeydown.asp
Use this in code-behind
if(Regex.IsMatch(yourStringToValidate,"^[a-zA-Z0-9\\\$]+$")
{
//Place your msg
}
else
{
//Place your validation msg
}
Try using the MaskedTextBox and set the mask to some thing like this:
maskedTextBox1.Mask = "\d*";
This code should be placed within head section of html.
I have used Jquery library to validate purpose
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mytext').keydown(function(e) {
if (e.shiftKey) e.preventDefault();
else {
var nKeyCode = e.keyCode;
//Ignore Backspace and Tab keys
if (nKeyCode == 8 || nKeyCode == 9) return;
if (nKeyCode < 95) {
if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
} else {
if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
}
}
});
});
</script>
Html code
<input type="text" id="mytext">
Related
I am trying to make it that on page load in the code behind, I disable a button in the radmenu using javascript
If I run my javascript in the console window in the browser to test then the button will disable. so that proofs that the JavaScript works.
the error is : cant find object - $find('myRadMenu') and the name is correct, so it has something todo with when the radmenu is rendered so I tried a wrap my script in a document.ready but that also won't work
'' not working with document.ready
' Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' ClientScript.RegisterStartupScript(Me.GetType(), "test", "<script type='text/javascript'> $(document).ready(function(){$find('myRadMenu').findItemByText('MyButton').disable();}); </script>")
' End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ClientScript.RegisterStartupScript(Me.GetType(), "test", "<script type='text/javascript'> $find('myRadMenu').findItemByText('MyButton').disable(); </script>")
End Sub
Do you know how to disable a radmenu button from javascript that is called from the vb.net page load function.
It must be done this way as I have other javascript that needs to fire
Please try with the below code snippet.
JS
function DisabelMenu(MenuText) {
setTimeout(function () { SetSettingAfterSometime(MenuText) }, 100);
}
function SetSettingAfterSometime(MenuText) {
var menu = $find("<%=RadMenu1.ClientID%>");
menu.findItemByText(MenuText).disable();
}
CS
RegisterStartupScript(this, this.GetType(), "test123", "DisabelMenu('test2');", true);
If you get the null then increase the timeout delay.
I would like to get some help on a unique processing issue. I am looking for a specific solution given these constraints.
I have a popup aspx page that receives data from a parent page gridview Edit click. There is a great deal of parsing of data from parent page to pop up as the data is being translated in pop up, then sent back to parent page to be reassembled in the original text block before update.
When the popup passes the data back or is canceled, the parent page gridview is still in Edit mode.
I would like to pass the Cancel or Update button click from the popup to the parent page gridview so it can complete the update or cancel event without asking the user to click the corresponding command button link from the gridview edit mode, to Update or Cancel.
I am really looking for a tutorial, links or sample code as I want to fully understand how to do this.
UPDATE: There is also a jquery UIBlocker on the Parent page to prevent the user from returning to the page until the PopUp page processing has been completed. Below is the critical code:
PARENT Page:
function parentFunc(a) {
// Unblocks on return from popup page.
$.unblockUI({});
document.getElementById("<%=Textbox1.ClientID %>").value = a;
alert("Please complete the update by entering a Brief Description then clicking the UPDATE link!!");
}
function parentCancel(s) {
// Unblocks because of cancel from popup page.
// var a = 0;
$.unblockUI({});
alert("Please click the Cancel link to complete the Cancel process!!");
}
PARENT PAGE Code Behind, Row Updatinfg Event after building array of strings to pass to POPUP page.
' Sets up popup to open when row selected for edit is cycled.
If IsPostBack Then
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
If Session("updateComplete") <> "Y" And Session("CancelUpdate") <> "Y" Then
Dim BrowserSettings As String = "status=no,toolbar=no, scrollbars =yes,menubar=no,location=no,resizable=no," & "titlebar=no, addressbar=no, width=850, height=800"
Dim URL As String = "NewpttStringPopUp.aspx"
Dim dialog As String = URL
Dim scriptText1 As String = ("<script>javascript: var w = window.open('" & URL & "','_blank','" & BrowserSettings & "'); $.blockUI({ message: '<h1>Please translate text and click Submit...</h1>' }); </script>")
ScriptManager.RegisterStartupScript(Me, GetType(Page), "ClientScript1", scriptText1, False)
Session("updateComplete") = "N"
End If
End If
End If
POPUP Page:
function closeform() {
alert("Please click the Cancel Button at the buttom of the page to Cancel the process!!");
return "Please click the Cancel Button at the buttom of the page to Cancel the process!!";
}
function handleWindowClose() {
if ((window.event.clientX < 0) || (window.event.clientY < 0)) {
event.returnValue = "If you have made any changes to the fields without clicking the Save button, your changes will be lost.";
}
}
function callParentFunc()
{
var w = window.opener;
var a;
if (!w.closed) {
var val = w.parentFunc(a);
self.close();
}
this.window.focus()
}
function callParentCancel() {
var w = window.opener;
var s;
if (!w.closed) {
var val = w.parentCancel(s);
self.close();
}
}
POPUP.ASPX.VB code behind CANCEL BUTTON
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
' Cancel Button so that no update is processed.
' Sets flag to prevent java popup from reopening after RowUpdating event. Occurs in RowDataBound event.
'Dim s As String = "c"
Dim strScript2 As String = "callParentCancel();"
ClientScript.RegisterStartupScript(GetType(Page), "callParentCancel", strScript2.ToString, True)
Session("UpdateEnd") = "Y"
Session("CancelUpdate") = "Y"
'Response.Write("<script>window.close();</script>")
End Sub
POPUP.ASPX.VB code behind SUBMIT BUTTON
Process of building the arrary is not displayed for breivity..
Session("returnTranslation") = arReturn
' Page.PreviousPage.Focus()
Dim strScript As String = "callParentFunc();"
ClientScript.RegisterStartupScript(GetType(Page), "callParentFunc", strScript.ToString, True)
' Sets flag to prevent java popup from reopening after RowUpdating event. Occurs in RowDataBound event.
Session("updateComplete") = "Y"
Had a problem with preventing the popup from reloading. So there is an if condition in the load event. A dynamic number of controls are built on the popup as literals. So the Page Init event and Page Load event fire on non Postback to rebuild the controls.
thanks, all suggestions will be reviewed.
Your best bet is to create a JavaScript function on the parent, and use window.opener to access it from the popup:
On the parent
processGridCommand = function(command){
__doPostBack("<%= GridView1.ClientID %>", command);
return false;
}
From the child
<script type="text/javascript">
updateParentGrid = function(command){
if (window.opener){
window.opener.processGridCommand(command);
}
return false;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Click" OnClientClick="return updateParentGrid('Update');" />
Handling the postback on the parent
This will trigger a postback on the parent, and overriding the RaisePostBackEvent method in the code-behind, you can handle it as needed:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
switch (eventArgument)
{
"Update":
//perform update logic
break;
"Cancel":
//cancel edit mode
break;
}
}
}
i want to use jquery ui auto complete plugin in asp.net.
this is my behind code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim locations As String() = New String() {"Las Vegas", "Los Angeles", "Tampa", "New York", "s", "sss"}
Dim jsArray As String = GetJSArrayForVBArray(locations)
Me.ClientScript.RegisterArrayDeclaration("usernames", jsArray)
End Sub
Private Function GetJSArrayForVBArray(ByVal vbArray As String()) As String
Dim myResult As New StringBuilder()
For Each item As String In vbArray
With myResult
.Append(",'" & item & "'")
End With
Next
If (myResult.Length > 0) Then
Return myResult.ToString().Substring(1)
Else
Return ""
End If
End Function
this is html code :
<script type="text/javascript">
$(function () {
var availableTags = new Array();
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
what is the problem?
it does not work.
when i filling array in aspx page it works but when i want to fill in behind code not.
thanks.
Try changing your JS to this:
<script type="text/javascript">
$(function () {
$("#tags").autocomplete({
source: usernames
});
});
</script>
If I'm guessing at your .Net code correctly, you're registering "usernames" as the javascript array, but trying to use the empty 'availableTags' as your autocomplete source.
Note: this may be completely off-base here - I haven't actually used ClientScript.RegisterArrayDeclaration or the jQuery autocomplete plugin in code I've written before.
Is there any way for me too loop though all controls on an asp.net pannel, and for each of the controls check the type to see if it is of asp type TimeInput?
The JS basicly needs to replicate this serverside VB.net code
'this is checking that something has been entered into at least one of the time input boxes
Protected Sub valCusAllTextBox_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles valCusAllTextBox.ServerValidate
'When the Save or Submit button is clicked the Page.IsValid() command causes the "valCusAllTextBox" custom validator control
'(which was dragged on to the page) to call this event - where we do our customised error checking
args.IsValid = False 'args.IsValid is a system function
'check all controls within the Overtime Claim panel
For Each ctrl As Control In pnlOvertimeClaim.Controls
If TypeOf ctrl Is TimeInput Then
If CType(ctrl, TimeInput).TimeInMinutes <> 0 Then
args.IsValid = True
Exit For
End If
End If
Next
If txtOnCallAllow.Text.Trim() <> "" Then
args.IsValid = True
End If
If txtMealAllow.Text.Trim() <> "" Then
args.IsValid = True
End If
End Sub
you can use this script to find specific control from the panel,
Put script at the end of page,
<script type="text/javascript" language="javascript">
var pnl = document.getElementById('pnl')
var array = pnl.getElementsByTagName("a");
for (var n = 0; n < array.length; ++n) {
alert("anchor");
}
var array = pnl.getElementsByTagName("img");
for (var n = 0; n < array.length; ++n) {
alert("Image");
}
Like this is your panel and you want to iterate specific control.
<asp:Panel runat="server" ID="pnl">
<a id="sd" href=""></a>
<img src="" />
<a id="A1" href=""></a>
</asp:Panel>
How to detect/track/check postback in javascript(e.g in asp.net Page.isPostBack())?
Any suggestion?
ASPX:
<input type="hidden" id="_ispostback" value="<%=Page.IsPostBack.ToString()%>" />
Client-side Script:
function isPostBack() { //function to check if page is a postback-ed one
return document.getElementById('_ispostback').value == 'True';
}
PS: I have not tested it but I've done somthing similar before and it works.
In some cases, you may want to check for postback without any server-side code. For example, in SharePoint, you cannot have code blocks in SharePoint Designer pages, so you can't use any solution that requires <%=something %>. Here is an alternative that involves no server-side code:
<script type="text/javascript">
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
document.write('<span style="color:red;">Your search returned no results.</span><br/>');
}
</script>
One caveat (or feature, depending on how you look at it), this will detect not just postbacks, but any instance where the page links to itself.
If you want to check whether the current page will be a postback if the user clicks on a submit button, you can check for the presence of ViewState:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="xxxxx" />
You can use something like document.getElementById("__VIEWSTATE") or the jQuery equivalent.
However, if you want to see whether the current page was generated in response to a postback, then you need to insert that data into the page on the server side first.
For example:
function isPostBack() {
return <%= Page.IsPostBack %>;
}
As JavaScript shouldn't be written with server-side code, and injecting new elements into the page seems like overkill, it seems to me that the simplest solution is to add [datat-*] attributes to the <head> element:
In Page_Load:
Page.Header.Attributes["data-is-postback"] IsPostBack ? "true" : "false";
This can then be accessed as:
jQuery:
$('head').data('isPostback');
Vanilla JS:
document.head.getAttribute('data-is-postback') === 'true';
Of course, if you treat the [data-is-postback] attribute as a boolean attribute, you could alternatively use:
In Page_Load:
if (IsPostBack)
{
Page.Header.Attributes.Add("data-is-postback", "");
}
else
{
Page.Header.Attributes.Remove("data-is-postback");
}
jQuery:
$('head').is('[data-is-postback]');
Vanilla JS:
document.head.hasAttribute('data-is-postback')
I have a solution that worked for me.
// Postback catch
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert("post back");
});
See following:
<script type="text/javascript">
function invokeMeMaster() {
var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
if (chkPostBack == 'false') {
alert('Only the first time');
}
}
window.onload = function() { invokeMeMaster(); };
</script>
You can only keep track of the postback if you are using AJAX requests or have a hidden field of some sort that the javascript reads on page load. Otherwise the page is regenerated and all POST data is lost; as you would expect and hope.
on Page_Load on your server-side :
The following uses an overload of RegisterClientScriptBlock() that will surround our string with the needed script tags
Server-Side
if (Page.IsPostBack){
ClientScript.RegisterClientScriptBlock(GetType(),
"IsPostBack", "var isPostBack = true;", true);
}
Then in your script which runs for the onLoad, check for the existence of that variable.
if (isPostBack){
//do something here
}
This should work for ASP.Net pages without relying on a backend supplied variable/control:
function isPostBack(frmID) {
var eventtarget = "";
var eventargument = "";
if (!!frmID) {
if (document.forms.length == 0) return false;
sForm = document.forms[0];
}
else {
sForm = document.getElementById(frmID);
if (!sForm) return false;
}
if (sForm.__EVENTTARGET) eventtarget = sForm.__EVENTTARGET.value;
else return false;
if (sForm.__EVENTARGUMENT) eventargument = sForm.__EVENTARGUMENT.value;
else return false;
if (eventtarget != "" || eventargument != "") return true;
else return false;
}
This is a simple JS way to determine the status of IsPostBack that I just got working in the Body of my ASPX page; needed to cause a PostBack during PageLoad for a project.
<script type="text/javascript">
if ('False' === '<%= Page.IsPostBack.ToString()%>')
{
__doPostBack();
}
</script>
Here is solution using jQuery:
$("a[href^='javascript:__doPostBack']").click(function () {
alert('ok');
});