How to handle keydown Event in asp.net Textbox? - c#

I have a textbox in web form(asp.net). when user already keyin data, then they will press Enter key, so that the data will be update to database.
Is there any way possible to perform this?

function InitTextBox() {
//var _txt = $('#<%= txt.ClientID%>'); or
var _txt = $('input:[id*="txtId"]');
if (_txt.length < 1) return;
_txt.get(0).autocomplete = 'off';
_txt.on('keydown', function (evt) {
var _self = $(this);
event = evt ? evt : window.event;
if (event.keyCode == 13) {
if ($.browser.msie)
{ event.cancelBubble = true; event.returnValue = false; }
else { event.preventDefault(); }
if (_self.val().length > 0 && _self.val().match(/^\s*$/) == null)
__doPostBack(_self.attr('name'), '');
}
});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTextBox);
And set autopostback for textbox to false, please

Dino Esposito had wrote about this a while back. You wouldn't necessarily need a custom control, but can use his JavaScript.
If you have a control wrapped around a Panel, and you have the DefaultButtonID property set, the panel will trigger a postback on enter too by clicking the desired button specified by the ID. That's another way.

Related

Prevent Key Event on DevExress ASP.NET MVC SpinEdit

In a form, I have a spin edit control like this:
formLayoutSettings.Items.Add(i =>
{
i.FieldName = "FieldA";
i.NestedExtension().SpinEdit(s =>
{
s.Properties.MinValue = 1;
s.Properties.MaxValue = 9999999999999;
s.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
s.Properties.ClientInstanceName = "seFieldA";
s.Properties.Increment = 10;
s.ShowModelErrors = true;
s.Width = Unit.Percentage(100);
s.Properties.AllowMouseWheel = false;
s.Properties.ClientSideEvents.KeyDown = "OnFieldAKeyDown"; // This is the event heandeler
});
});
And the function:
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
ASPxClientUtils.PreventEventAndBubble(e.htmlEvent); // this doesn't work
ASPxClientUtils.PreventEvent(e.htmlEvent); // this either
}
}
My aim is to prevent the spin edit control value from changing when the user presses the Up key or Down keys. When I debug this, the if test inside the OnFieldAKeyDown works but PreventEventAndBubble and PreventEvent fails miserably. Also, is there any other way to do this with jquery ??
Thanks.
AFAIK, there is a workaround to prevent a user incrementing/decrementing SpinEdit value using up/down arrow keys without using PreventEvent or PreventEventAndBubble. When there's no public method available on JS side, you can try restore SpinEdit previous value in KeyDown event handler like this:
<script type="text/javascript">
function OnFieldAKeyDown(s, e) {
if (e.htmlEvent.keyCode == 38 || e.htmlEvent.keyCode == 40) {
// check if ASPxClientSpinEdit exists
if (typeof ASPxClientSpinEdit !== "undefined") {
ASPxClientSpinEdit.prototype.OnPageOrArrowKeyDown = function() {
// when user tries either increment or decrement, it returns last value instead
if (s.GetValue() != s.lastChangedValue) {
s.SetValue(s.lastChangedValue);
}
// if spinedit's minimum & maximum values also affected, set current limit
else {
s.maxValue = ASPxClientSpinEdit.MaxValue;
s.minValue = ASPxClientSpinEdit.MinValue;
}
}
}
}
}
</script>
Combine this function with jQuery may possible, any suggestions welcome.
Reference: https://www.devexpress.com/Support/Center/Question/Details/Q254514

How to make ajax auto-complete compulsory?

I want to force the user to select from the auto-complete options.
NB: I do not want to use a drop down menu.
Try using this
var isItemSelected = false;
//Handler for AutoCompleter OnClientItemSelected event
function onItemSelected() {
isItemSelected = true;
}
//Handler for textbox blur event
function checkItemSelected(myTextBox) {
if (!isItemSelected) {
alert("Please select item from the list only!");
myTextBox.focus();
}
else {
//reset isItemSelected
isItemSelected = false;
}
}
And then throw this in the Textbox:
onblur="checkItemSelected(this)"
Well i have this forum for the references .
Forum,
You'll need to use the select and focus options to support this.
Fiddle example
focus: function( event, ui ) {
$( "#tags" ).val( ui.item.label );
return false;
},

Modal Window Loses Focus when Tab and Shift+Tab is Pressed

I'm Having a hard time Coding and Trying different approaches on how to catch the tab and Shift+tab when Modal Window is open , It loses focus and Jumps to Text box at the background ,
Can someone Help me with this situation. Thanks
editwindow = $("#modalWindow").kendoWindow({
title: "Edit Person Information",
modal: true,
visible: false,
resizable: false,
width: 600
}).data("kendoWindow");
Then
<div id="modalWindow" class="main">
#using (Html.BeginForm("Edit", "People", FormMethod.Post, new { id = "PeopleForm" }))
Use this example
$("#modalWindow").kendoWindow({
close: onClose,
**activate: onActivate**
});
function onActivate(e) {
var windowElement = this.wrapper,
windowContent = this.element;
$(document).on("keydown.kendoWindow", function(e) {
var focusedElement = $(document.activeElement);
if (e.keyCode == kendo.keys.TAB && focusedElement.closest(windowElement).length == 0) {
windowContent.focus();
}
});
}
Check This
I tried other workarounds unsuccessfully. The solution we're using now follows (this is in our global keydown event handler). Note - we're ignoring tabindex values here - simply identifying 1st and last :input elements.
if (key == kendo.keys.TAB) {
var $currentOpenWindow = $(".k-window:visible"); // test if there is a window that is currently displayed
var $inputElements = $currentOpenWindow.find(":input"); // includes buttons
// if a dialog is currently displayed, don't allow the user to tab out of the dialog into the base form. Per Casey on 1/2016, we don't need to support nested dialogs.
if ($currentOpenWindow.length > 0 && $inputElements.length > 0) {
Utility.log(1, "Enforcing tab within displayed window $currentOpenWindow.length:", $currentOpenWindow.length);
var isValid = true;
if (e.shiftKey) {
if (document.activeElement == $inputElements[0])
isValid = false;
}
else {
if (document.activeElement == $inputElements[$inputElements.length-1])
isValid = false;
}
if (!isValid) { // Cancel the tab key - this will prevent the browser from changing focus to any other element
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
}
}

Detecting focussed control in C#

I have an update panel which is causing a postback on part of the page and after postback the control that had focus (which is not in the update panel) loses focus. How can I identify which control had focus and save that value, so that I can refocus to it when the page reloads. Thank you.
First I bind the focus on all input and keep the last focused control ID. Then after the UpdatePanel finish the load, I set the focus to the last one
// keep here the last focused id
var LastFocusedID = null;
function watchTheFocus()
{
// on every input that get the focus, I grab the id and save it to global var
$(":input").focus(function () {
LastFocusedID = this.id;
});
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
}
// after the updatePanel ends I re-bind the focus, and set the focus
// to the last one control
function EndRequest(sender, args) {
if(LastFocusedID != null)
$('#' + LastFocusedID).focus();
watchTheFocus();
}
jQuery(document).ready(function()
{
watchTheFocus();
});
The only think is that I use jQuery to make it, but I present here my idea, you can make it with little more code with out jQuery.
You can get what element has focus with javascript using the activeElement and hasFocusproperty to HTMLDocument object.It might not be supported by all since it's HTML5.
You can solve like this
var last_focused = null;
$(function () {
//store last focused element.
$("input").live("focus", function(){
last_focused = $(this);
});
});
//in Script manager
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
function pageLoaded(sender, args)
{
if(last_focused != null)
{
last_focused.focus();
}
}

How to make the Default focus in content page from master page

I have masterpage with content place holder. i have contentpage which is using master page . in all my content page i need to default focus on the text box so that the user can directly type in text box instead moving the mouse over the textbox. in some page there is no text box so that i donnot nnet keep default focus over there
Is there any way i can do it in my master page once and can reuse that in all my content page
thank you
try using this...
((TextBox)Master.FindControl("txtRequiredFocus")).Focus();
You could include this in your master page's load event:
// if the ID is constant you can use this:
/*TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.FindControl("myTextBox");
*/
// this will look for the 1st textbox without hardcoding the ID
TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.Controls.OfType<TextBox>()
.FirstOrDefault();
if (textBox != null)
{
textBox.Focus();
}
This would match up with a content page that has the following markup:
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
</asp:Content>
EDIT: if LINQ isn't an option then you can use this instead:
foreach (Control control in Page.Controls[0].FindControl("ContentPlaceHolder1").Controls)
{
if (control is TextBox)
{
((TextBox)control).Focus();
break;
}
}
Indiscriminate JavaScript approach to selecting the first valid input field on a page:
function SelectFirstInput() {
var bFound = false;
for (f = 0; f < document.forms.length; f++) {
// for each element in each form
for (i = 0; i < document.forms[f].length; i++) {
// if it's not a hidden element
if (document.forms[f][i].type != "hidden") {
// and it's not disabled
if (document.forms[f][i].disabled != true) {
// set the focus to it
document.forms[f][i].focus();
var bFound = true;
}
}
// if found in this element, stop looking
if (bFound == true)
break;
}
// if found in this form, stop looking
if (bFound == true)
break;
}
}
<script language="javascript" type="text/javascript" >
window.onload=function(){
var t= document.getElementById('<%=TextBox1.clientID %>');
t.focus();
}
</script>
If you use jQuery, a possible solution is:
Give the textbox you want to set focus to a special class. "focus" works well for this purpose.
Write code such as the following in your master page or included by your master page in a js script file:
$(document).ready
(
function()
{
//get an array of DOM elements matching the input.focus selector
var focusElements = $("input.focus").get();
//if a focus element exists
if(focusElements.length > 0)
{
focusElements[0].focus();
}
}
);
A similar approach using vanilla JavaScript would be to tag the textbox with a special attribute. Let's use focus.
window.onload = function()
{
//get all input elements
var inputElements = document.getElementsByTagName("input");
var elementToFocus = null;
for(var i = 0; i < inputElements.length; ++i)
{
var focusAttribute = inputElements[i].getAttribute("focus");
if(focusAttribute)
{
elementToFocus = inputElements[i];
break;
}
}
if(elementToFocus)
{
elementToFocus.focus();
}
};
Control masterC =
Page.Master.FindControl("ContentPlaceHolder1");
TextBox TextBox1 =
masterC.FindControl("TextBoxUsername") as TextBox;
TextBox1.Focus();

Categories