I have an ASP.net textbox that the user needs to enter emails. I need to detect when the user types a semi-colon(;) then unhide a textbox and set the focus to that textbox.
Disclaimer: This might seem a little "hacky" and I'm sure there are better ways of doing this.
You can use the onkeypress of the textbox, set that to a JavaScript function. In the JavaScript function, programmatically "unhide" and give focus to your other textbox on the client-side. No post-back required.
JavaScript:
function checkForSemicolons(event) {
var txtEmail = document.getElementById("<%= txtEmail.ClientID %>");
if (event.keyCode === 59) {
// unhide other textbox and give focus to it
}
}
ASPX:
<asp:TextBox ID="txtEmail" onkeypress="checkForSemicolons(event)" runat="server" />
OnKeypress event is fired from the client side, so you need do catch that from the client script.
You can use javascript to cause a postback and than send the parameters to the server-side, but usually you can handle all from the client.
On jquery you would have somethig like this:
$("TextboxID").keypress(function(e){
//do something
//If you want to cause a postback use " __doPostBack('EventTaarget','Parameters');"
//you can capture the key that was pressed on e.keycode (for keycodes list, check: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes)
})
On the code behind you can add some code to capture this event on page_load.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.Request("__EVENTTARGET") Is Nothing Then
'do something - you can use the Parameter with: Me.Request("__EVENTARGUMENT")
end if
end sub
Related
I am in the process of adding a filter to asp grid. I have succeeded in showing a text box for filtering in header.
I need to fire server code for filtering whenever user presses enter key in textbox.
So I started with adding event like
txtFilter.Attributes.Add("onkeyup", keyUpScript);
Then I added client script as
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "registerkeyUPScript", registerkeyUPScript, true);
where
string keyUpScript = "keyUPScript(event);";
string registerkeyUPScript = "function keyUPScript(e){\n"
+ "var unicode=e.keyCode? e.keyCode : e.charCode;\n"
+ "if(unicode == '13')\n"
+"{\n"
+" //PostBack code"
+"}"
+"}";
Now how could I postback when ever user enters a string in text box and presses enter key. I also need to rebind the filtered data back to grid
Any help will be appreciated.
You can try using this line of code to attach an onkeyup to your TextBox to only fire a postback event when Enter is pressed. Also, just in case you want to attach an OnTextChanged event for that particular TextBox, you can do so and that will be called as well when the page postbacks.
Use this in your Page_Load event :
TextBoxID.Attributes.Add("onkeyup", "return (event.keyCode==13);");
And this is the OnTextChanged event just in case if you want to attach :
protected void T1_TextChanged(object sender, EventArgs e)
{
//your logic goes here
}
Hope this helps.
I have asp.net Login control, example
<asp:Login ID="Login" onauthenticate="LoginAuthenticateEvent" runat="server"/>
have *.cs function like
protected void LoginAuthenticateEvent(object sender, AuthenticateEventArgs e)
{
//..
}
But it launch Authenticate only if pressing login Button, not by 'Enter' in textboxes.
So I decided to set this event to javascript 'onkeypress' event, and want it to check if keycode is 13(Enter) - and launch LoginAuthenticateEvent.
But there is problem - to call C# function from JS function should be static, but in my case it is 'protected void'
In JS(jQuery) code I get necessary element like this:
var tboxUserName = $("input[name*='UserName']");
I understand that there should be somethin like
tboxUserName.attr("onkeypress","....");
But how to hang there key check and make it such as onauthenticate="LoginAuthenticateEvent"?
upd.: Tried find control on Server side, and add TextChanged event there
TextBox tb = (TextBox)Login.FindControl("UserName");
tb.TextChanged += tbox_TextChanged;
But 'TextChanged' event fires only on focus change(when click other textbox or button) - but I need to check every keypress. So question is still opened.
Yes, solution from #Dave Becker is working. In my case my Login control is branded and there was not Button, but ImageButton. In this the code looks like this:
<asp:Panel ID="panelLogin" runat="server" DefaultButton="Login$LoginImageButton">
<asp:Login ID="Login" onauthenticate="LoginAuthenticateEvent" runat="server">
</asp:Login>
</asp:Panel>
wondering if this is possible, currently using this to click a 'clear' button, then it clears UPIN;
Protected Sub clear(ByVal Sender As Object, ByVal e As System.EventArgs)
UPIN.Text=String.Empty
End Sub
But I want it to clear whichever textbox is in focus! for example;
focusedstring.Text=String.Empty
Again is it possible without masses of JS or anything?
You should do it on client side (edit: as suggested by MightyLampshade you can find on of 1000 examples here), you do not need a round-trip to server for that. If you have, let's say, a clear button:
$("#clear").click(function() {
$(".can-be-cleared").val("");
});
Please note that this will clear all elements with class can-be-cleared (I assume you may do not want to clear each input but a specific set, if it's not the case just replace it with input[type=text]).when you click an element with id clear.
If each "clear" button has to be tied with a single specific text box then you have to repeat them (because when you click on the button textbox won't be focused any more). As alternative you may remember last focused text box. Let's see both:
<input type="text" id="textbox1"/>
<button class="clear-button" data-textbox="textbox1">clear</button>
JavaScript for this is:
$(".clear-button").click(function() {
$("#"+$(this).data("textbox")).val("");
});
Simpler alternative (I prefer this if you do not have any other special requirement) may be to keep track of last focused textbox:
var lastFocused = undefined;
$("input[type=text]").focus(function () {
lastFocused = $(this);
});
$("#clear-field").click(function () {
if (lastFocused !== undefined) {
lastFocused.val("");
}
});
Of course do not forget to match $("#clear-field") with right ID you used for your clear button, in this case I assume:
<button id="clear-field">Clear</button>
Anyway if you really need some server side processing (for any other reason), TextBox that generated event is in sender parameter:
Dim textbox As TextBox = DirectCast(sender, TextBox)
textbox.Text = String.Empty
can you try this:
$('input[type=text]').focus(function() {
$(this).val('');
});
Its simple with Jquery..no need to write masses of lines of code.
Updated:
If you do want to Clear on button click:
$("#Clear").click(function(){
$('input[type=text]').focus(function() {
$(this).val('');
});
});
I would like to know, is it possible to cancel the next JavaScript event in the queue from another event?
Problem:
I have two ASP.Net controls,
Age - TextBox
Save - Button
There are two JavaScript validation functions,
ValidateAge() - checks for Valid age (0 >= Age <= 140), provides an alert if invalid
ValidatePage() - checks for all the required fields in the page and saves if all the required fields are filled in
<asp:TextBox ID="txtAge" TabIndex="1" DataType = "String" runat="server" MaxLength="50" CssClass="textBox" Style="width: 150px" CausesValidation="true" onblur="return ValidateAge();"></asp:TextBox>
and there is an access key defined for button,
<asp:Button ID="btnSave" AccessKey="S" AssociatedControlID="btnSave" TabIndex="1" runat="server" CssClass="ButtonSaveNew" onclick="return ValidatePage();"></asp:Button>
Now if I press Alt+S with an invalid age in the Age field first the onblur of Age gets called (as I have set the AssociatedControlID) and then the onclickof the save button is called.
Now what happens is that irrespective of the age is valid or invalid the save gets executed.
I need to cancel the onclick event of button from the onblur event of the textbox, if the age is not valid.
What is probably happening is that your form is submitting, and thus the button isn't actually firing the onclick event (since it's not being clicked as such!). You'll likely notice the same behaviour if you hit enter within one of the form fields (even with the txtAge field!), as this also causes a form submit.
The easiest thing to do in this case is register the ValidatePage function as a handler for the submit event on the form:
<form onsubmit="ValidatePage()">
Though i appreciate you're using WebForms and thus it's likely this will be difficult. Whenever i've done client-side validation in WebForms I've always relied on the jQuery.validation plugin. If you're already reliant on jQuery this provides a very neat model to do validation. It doesn't play well with WebForms out of the box and you need to do a little playing around to get it working. Dave Ward's post here will likely be of help: http://encosia.com/using-jquery-validation-with-asp-net-webforms/
Is it possible cancel a java script event from another event?
No, generally it is not. Also, the blur event can't be canceled, and according to how to prevent blur() running when clicking a link in jQuery? it is complicated to hold the focus.
Yet, I don't think holding the focus when the user tries to leave a element (and focus the next input) is very userfriendly - only show a validation fail for the leaved input. The only event you really should prevent is submit, when validation has failed, and you then could focus the first invalid field.
var ageValid;
$("#txtAge").change(function validateAge(e) {
if(!isNaN(this.value) && this.value >= 0) {
ageValid = true;
} else {
$(this).addClass("invalid");
ageValid = false;
}
}).change();
$("#formid").submit(function validatePage(e) {
// maybe calls to the single validation functions?
if (! ageValid) {
e.preventDefault();
$("#txtAge").focus();
return false;
}
});
Im designing a user control that has the following:
a textbox called 'AddressInput'
a google maps plugin
a linkbutton
a textbox for the marker title called 'MarkerTitleInput'
a "Submit" button
The problem is this:
When the linkbutton is clicked, I need to validate that AddressInput was completed, but nothing else
When the submit button is clicked, I need to validate that AddressInput and MarkerTitleInput were both completed.
So my first two problems are:
1) How do i validate certain fields from a linkbutton, without submitting the form
2) How do i validate all fields from the form being submitted
My other problem is that when the linkbutton is clicked, my code runs a lookup against Google's Geocode to get an address. I was going to create an additional validation method to handle when an address is not found, but using a validator means the json request is sent everytime a key is pressed, which is too much - i only want the validation to run when the linkbutton is clicked. I have tried (selector).validate({ onkeyup:false }) with no avail. Is it perhaps possible to manually set whether the .valid() method thinks the form is valid?
Thanks
Al
$("form").validate({
groups:{
pg1:"_Phone1 _Phone2 _Phone3",
pg2:"dob_month dob_day dob_year"
},
errorPlacement:function(error, element){
if(element.attr("name")=="_Phone1"|| element.attr("name")=="_Phone2" || element.attr("name")=="_Phone3"){
error.insertAfter("#_Phone3")
}
else if
(element.attr("name")=="dob_month"|| element.attr("name")=="dob_day" || element.attr("name")=="dob_year"){
error.insertAfter("#dob_year")
}
else
error.insertAfter(element);
},
});
});
Give each of the two buttons a unique class (for ease of targeting in jQuery).
Give each class an OnClick event.
Validate in the OnClick event.
If the validation succeeds, return true.
Else return false.