Asp.Net Form DefaultButton Error in Firefox - asp.net

The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).
Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.
For more information on the bug, read it here.
This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.
Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.

I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]
http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html.
You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.
<div onkeypress="return FireDefaultButton(event, '<%= aspButtonID.ClientID %>')">
(your form goes here)
</div>
Here's the function.
function FireDefaultButton(event, target)
{
// srcElement is for IE
var element = event.target || event.srcElement;
if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase()))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && "undefined" != typeof defaultButton.click)
{
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
return false;
}
}
return true;
}

It seems that the fix codesta.com that harpo link to is no longer necessary, since the fix event.srcElement is not integrade in ASP.NET 3.5. The implementation of DefaultButton does however still have some problems, because it is catching the Enter key press in too many cases. For example: If you have activated a button in the form using tab, pressing Enter should click on the button and not submit the form.
Include the following JavaScript code at the bottom of your ASP.NET web page to make Enter behave the way it should.
// Fixes ASP.NET's behavior of default button by testing for more controls
// than just textarea where the event should not be caugt by the DefaultButton
// action. This method has to override ASP.NET's WebForm_FireDefaultButton, so
// it has to included at the bottom of the page.
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (!(
src
&&
(
src.tagName.toLowerCase() == "textarea"
|| src.tagName.toLowerCase() == "a"
||
(
src.tagName.toLowerCase() == "input"
&&
(
src.getAttribute("type").toLowerCase() == "submit"
|| src.getAttribute("type").toLowerCase() == "button"
|| src.getAttribute("type").toLowerCase() == "reset"
)
)
|| src.tagName.toLowerCase() == "option"
|| src.tagName.toLowerCase() == "select"
)
)) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof (defaultButton.click) != "undefined") {
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}

For this particular issue, the reason is because javascript generated by
ASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in
FireFox (use event.target instead):
function WebForm_FireDefaultButton(event, target) {
if (!__defaultFired && event.keyCode == 13 && !(event.srcElement &&
(event.srcElement.tagName.toLowerCase() == "textarea"))) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) !=
"undefined") {
__defaultFired = true;
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
If we change the first 2 lines into:
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element &&
(element.tagName.toLowerCase() == "textarea"))) {
Put the changed code in a file and then do
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptInclude("js1", "JScript.js");
}
Then it will work for both IE and FireFox.
Source:
http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html

Related

how to set default button in different tabs?

I have a content page that have 4 different tabs. I use following jQuery to control the tabs. I need to set the default button for each tab, so that when the user clicks Enter, the event of the default button will be fired.
The keypress should do the work. But somehow, when I click Enter, the page is reloaded, not being submitted.
How can I change my code to have the page determine which button is the default button, depending on what user control or tab is active?
$(document).ready(function() {
var selected_tab = document.getElementById("<%=hfSelectedTab.ClientID %>");
//When page loads...
$(".tab_content").hide(); //Hide all content
if (selected_tab.value == 2) {
$("ul.tabs li:nth-child(2)").addClass("active").show();
$(".tab_content:nth-child(2)").show();
}
else if (selected_tab.value == 3) {
$("ul.tabs li:nth-child(3)").addClass("active").show();
$(".tab_content:nth-child(3)").show();
}
else if (selected_tab.value == 4) {
$("ul.tabs li:nth-child(4)").addClass("active").show();
$(".tab_content:nth-child(4)").show();
}
else {
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content
}
//On Click Event
$("ul.tabs li").click(function() {
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active ID content
if (activeTab == "#tab1")
selected_tab.value = 1;
else if (activeTab == "#tab2")
selected_tab.value = 2;
else if (activeTab == "#attachmentcontent")
selected_tab.value = 3;
else if (activeTab == "#kb") {
selected_tab.value = 4;
document.getElementById("<%=txtRootCause.ClientID %>").focus();
}
return false;
});
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return true;
}
});
});
My solution is to wrap each tab (defined by div) in an asp:Panel and set the Panel DefaultButton property.

QShortCut and QSpinBox conflict

I'm writing an application were i use my own shortcut. It looks like this:
myShortcut= new QShortcut(Qt::SHIFT + Qt::Key_B,this);
connect(myShortcut, SIGNAL(activated()), this, SLOT(setCameraBack()));
I defined it in the constructor of main widget and it works fine until i click one of the spinbox buttons which are also located on the main widget. After that my shortcut stop working and it doesn't work until i click push button or check box. When i do that everything is fine again. I'd like to add that after i click spinbox it seems to be "active" (because the cursor is still "blinking" on it) until i click one of the other buttons. Do you have any idea what is wrong? Is it some kind process or event problem? Thanks for all answers
~Marwroc
A shortcut is "listened for" by Qt's
event loop when the shortcut's parent
widget is receiving events.
When the QSpinBox has keyboard focus, then the QShortcut object's parent is no longer receiving events. Therefore, the shortcut does not work until keyboard focus is removed form the QSpinBox. You can change this behavior by passing Qt::WidgetWithChildrenShortcut or Qt::ApplicationShortcut to the QShortcut::setContext method of your QShortcut.
Before a shortcut is activated, the focus widget is given a ShortcutOverride event. If the event is accepted, the key event is passed along to the widget and the shortcut is not activated.
Source: https://wiki.qt.io/ShortcutOverride
Looking at Qt source
QAbstractSpinBox::event(QEvent *event)
{
Q_D(QAbstractSpinBox);
switch (event->type()) {
...
case QEvent::ShortcutOverride:
if (d->edit->event(event))
return true;
break;
...
}
return QWidget::event(event);
}
QAbstractSpinBox is allowing the internal edit to accept the event. QLineEdit defers to QLineControl. From qt/src/gui/widgets/qlinecontrol.cpp
case QEvent::ShortcutOverride:{
if (isReadOnly())
return false;
QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
if (ke == QKeySequence::Copy
|| ke == QKeySequence::Paste
|| ke == QKeySequence::Cut
|| ke == QKeySequence::Redo
|| ke == QKeySequence::Undo
|| ke == QKeySequence::MoveToNextWord
|| ke == QKeySequence::MoveToPreviousWord
|| ke == QKeySequence::MoveToStartOfDocument
|| ke == QKeySequence::MoveToEndOfDocument
|| ke == QKeySequence::SelectNextWord
|| ke == QKeySequence::SelectPreviousWord
|| ke == QKeySequence::SelectStartOfLine
|| ke == QKeySequence::SelectEndOfLine
|| ke == QKeySequence::SelectStartOfBlock
|| ke == QKeySequence::SelectEndOfBlock
|| ke == QKeySequence::SelectStartOfDocument
|| ke == QKeySequence::SelectAll
|| ke == QKeySequence::SelectEndOfDocument) {
ke->accept();
} else if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier
|| ke->modifiers() == Qt::KeypadModifier) {
if (ke->key() < Qt::Key_Escape) {
ke->accept();
} else {
switch (ke->key()) {
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Backspace:
case Qt::Key_Left:
case Qt::Key_Right:
ke->accept();
default:
break;
}
}
}
}
This code accepts most keys if the control key is not also pressed.
So the easiest solution is to change the shortcut to include the control modifier.
Alternatively, you can subclass the spin box and override the event function
bool MySpinBox::event(QEvent *event)
{
if( event->type() == QEvent::ShortcutOverride && !isReadOnly() )
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
// Ignore 'B' shortcuts
if( keyEvent->key() == Qt::Key_B )
{
Q_ASSERT( !event->isAccepted() );
return true;
}
return QSpinBox::event(event);
}
Have you tried MySpinBox -> setFocusPolicy (Qt::NoFocus) ?

How do I maintain focus position in UpdatePanel after page partial post back

I have four controls in a page with update panel. Initially mouse focus is set to first control. When I partially post back the page to server the focus automatically moves to first control from the last focused control from the control I have tabbed down to. Is there any way to maintain the last focus?
Take a look at Restoring Lost Focus in the Update Panel with Auto Post-Back Controls:
The basic idea behind the solution is to save the ID of the control
with input focus before the update panel is updated and set input
focus back to that control after the update panel is updated.
I come with the following JavaScript which restores the lost focus in
the update panel.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof(window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof(document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof(focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof(lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
I find this more elegant:
(function(){
var focusElement;
function restoreFocus(){
if(focusElement){
if(focusElement.id){
$('#'+focusElement.id).focus();
} else {
$(focusElement).focus();
}
}
}
$(document).ready(function () {
$(document).on('focusin', function(objectData){
focusElement = objectData.currentTarget.activeElement;
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(restoreFocus);
});
})();

Specifying maxlength for multiline textbox

I'm trying to use asp:
<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>
I want a way to specify the maxlength property, but apparently there's no way possible for a multiline textbox. I've been trying to use some JavaScript for the onkeypress event:
onkeypress="return textboxMultilineMaxNumber(this,maxlength)"
function textboxMultilineMaxNumber(txt, maxLen) {
try {
if (txt.value.length > (maxLen - 1)) return false;
} catch (e) { }
return true;
}
While working fine the problem with this JavaScript function is that after writing characters it doesn't allow you to delete and substitute any of them, that behavior is not desired.
Have you got any idea what could I possibly change in the above code to avoid that or any other ways to get round it?
Use a regular expression validator instead. This will work on the client side using JavaScript, but also when JavaScript is disabled (as the length check will be performed on the server as well).
The following example checks that the entered value is between 0 and 100 characters long:
<asp:RegularExpressionValidator runat="server" ID="valInput"
ControlToValidate="txtInput"
ValidationExpression="^[\s\S]{0,100}$"
ErrorMessage="Please enter a maximum of 100 characters"
Display="Dynamic">*</asp:RegularExpressionValidator>
There are of course more complex regexs you can use to better suit your purposes.
try this javascript:
function checkTextAreaMaxLength(textBox,e, length)
{
var mLen = textBox["MaxLength"];
if(null==mLen)
mLen=length;
var maxLength = parseInt(mLen);
if(!checkSpecialKeys(e))
{
if(textBox.value.length > maxLength-1)
{
if(window.event)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
Roll your own:
function Count(text)
{
//asp.net textarea maxlength doesnt work; do it by hand
var maxlength = 2000; //set your value here (or add a parm and pass it in)
var object = document.getElementById(text.id) //get your object
if (object.value.length > maxlength)
{
object.focus(); //set focus to prevent jumping
object.value = text.value.substring(0, maxlength); //truncate the value
object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
return false;
}
return true;
}
Call like this:
<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>
Things have changed in HTML5:
ASPX:
<asp:TextBox ID="txtBox" runat="server" maxlength="2000" TextMode="MultiLine"></asp:TextBox>
C#:
if (!IsPostBack)
{
txtBox.Attributes.Add("maxlength", txtBox.MaxLength.ToString());
}
Rendered HTML:
<textarea name="ctl00$DemoContentPlaceHolder$txtBox" id="txtBox" maxlength="2000"></textarea>
The metadata for Attributes:
Summary: Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
Returns: A System.Web.UI.AttributeCollection of name and value pairs.
use custom attribute maxsize="100"
<asp:TextBox ID="txtAddress" runat="server" maxsize="100"
Columns="17" Rows="4" TextMode="MultiLine"></asp:TextBox>
<script>
$("textarea[maxsize]").each(function () {
$(this).attr('maxlength', $(this).attr('maxsize'));
$(this).removeAttr('maxsize');
});
</script>
this will render like this
<textarea name="ctl00$BodyContentPlac
eHolder$txtAddress" rows="4" cols="17" id="txtAddress" maxlength="100"></textarea>
Another way of fixing this for those browsers (Firefox, Chrome, Safari) that support maxlength on textareas (HTML5) without javascript is to derive a subclass of the System.Web.UI.WebControls.TextBox class and override the Render method. Then in the overridden method add the maxlength attribute before rendering as normal.
protected override void Render(HtmlTextWriter writer)
{
if (this.TextMode == TextBoxMode.MultiLine
&& this.MaxLength > 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
}
base.Render(writer);
}
$('#txtInput').attr('maxLength', 100);
Use HTML textarea with runat="server" to access it in server side.
This solution has less pain than using javascript or regex.
<textarea runat="server" id="txt1" maxlength="100" />
Note: To access Text Property in server side, you should use txt1.Value instead of txt1.Text
I tried different approaches but every one had some weak points (i.e. with cut and paste or browser compatibility). This is the solution I'm using right now:
function multilineTextBoxKeyUp(textBox, e, maxLength) {
if (!checkSpecialKeys(e)) {
var length = parseInt(maxLength);
if (textBox.value.length > length) {
textBox.value = textBox.value.substring(0, maxLength);
}
}
}
function multilineTextBoxKeyDown(textBox, e, maxLength) {
var selectedText = document.selection.createRange().text;
if (!checkSpecialKeys(e) && !e.ctrlKey && selectedText.length == 0) {
var length = parseInt(maxLength);
if (textBox.value.length > length - 1) {
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
}
}
}
function checkSpecialKeys(e) {
if (e.keyCode != 8 && e.keyCode != 9 && e.keyCode != 33 && e.keyCode != 34 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40) {
return false;
} else {
return true;
}
}
In this case, I'm calling multilineTextBoxKeyUp on key up and multilineTextBoxKeyDown on key down:
myTextBox.Attributes.Add("onkeyDown", "multilineTextBoxKeyDown(this, event, '" + maxLength + "');");
myTextBox.Attributes.Add("onkeyUp", "multilineTextBoxKeyUp(this, event, '" + maxLength + "');");
Here's how we did it (keeps all code in one place):
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"/>
<% TextBox1.Attributes["maxlength"] = "1000"; %>
Just in case someone still using webforms in 2018..
Have a look at this. The only way to solve it is by javascript as you tried.
EDIT:
Try changing the event to keypressup.
The following example in JavaScript/Jquery will do that-
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function count(text, event) {
var keyCode = event.keyCode;
//THIS IS FOR CONTROL KEY
var ctrlDown = event.ctrlKey;
var maxlength = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val().length;
if (maxlength < 200) {
event.returnValue = true;
}
else {
if ((keyCode == 8) || (keyCode == 9) || (keyCode == 46) || (keyCode == 33) || (keyCode == 27) || (keyCode == 145) || (keyCode == 19) || (keyCode == 34) || (keyCode == 37) || (keyCode == 39) || (keyCode == 16) || (keyCode == 18) ||
(keyCode == 38) || (keyCode == 40) || (keyCode == 35) || (keyCode == 36) || (ctrlDown && keyCode == 88) || (ctrlDown && keyCode == 65) || (ctrlDown && keyCode == 67) || (ctrlDown && keyCode == 86))
{
event.returnValue = true;
}
else {
event.returnValue = false;
}
}
}
function substr(text)
{
var txtWebAdd = $("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val();
var substrWebAdd;
if (txtWebAdd.length > 200)
{
substrWebAdd = txtWebAdd.substring(0, 200);
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val('');
$("#<%=txtMEDaiSSOWebAddress1.ClientID%>").val(substrWebAdd);
}
}
This snippet worked in my case. I was searching for the solution and thought to write this so that it may help any future reader.
ASP
<asp:TextBox ID="tbName" runat="server" MaxLength="250" TextMode="MultiLine" onkeyUp="return CheckMaxCount(this,event,250);"></asp:TextBox>
Java Script
function CheckMaxCount(txtBox,e, maxLength)
{
if(txtBox)
{
if(txtBox.value.length > maxLength)
{
txtBox.value = txtBox.value.substring(0, maxLength);
}
if(!checkSpecialKeys(e))
{
return ( txtBox.value.length <= maxLength)
}
}
}
function checkSpecialKeys(e)
{
if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
#Raúl Roa Answer did worked for me in case of copy/paste. while this does.
$("textarea[maxlength]").on("keydown paste", function (evt) {
if ($(this).val().length > $(this).prop("maxlength")) {
if (evt.type == "paste") {
$(this).val($(this).val().substr(0, $(this).prop("maxlength")));
} else {
if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
evt.returnValue = false;
evt.preventDefault();
}
}
}
});
you can specify the max length for the multiline textbox in pageLoad Javascript Event
function pageLoad(){
$("[id$='txtInput']").attr("maxlength","10");
}
I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function
This is the same as #KeithK's answer, but with a few more details. First, create a new control based on TextBox.
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyProject
{
public class LimitedMultiLineTextBox : System.Web.UI.WebControls.TextBox
{
protected override void Render(HtmlTextWriter writer)
{
this.TextMode = TextBoxMode.MultiLine;
if (this.MaxLength > 0)
{
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());
}
base.Render(writer);
}
}
}
Note that the code above always sets the textmode to multiline.
In order to use this, you need to register it on the aspx page. This is required because you'll need to reference it using the TagPrefix, otherwise compilation will complain about custom generic controls.
<%# Register Assembly="MyProject" Namespace="MyProject" TagPrefix="mp" %>
<mp:LimitedMultiLineTextBox runat="server" Rows="3" ...
Nearly all modern browsers now support the use of the maxlength attribute for textarea elements.(https://caniuse.com/#feat=maxlength)
To include the maxlength attribute on a multiline TextBox, you can simply modify the Attributes collection in the code behind like so:
txtTextBox.Attributes["maxlength"] = "100";
If you don't want to have to use the code behind to specify that, you can just create a custom control that derives from TextBox:
public class Textarea : TextBox
{
public override TextBoxMode TextMode
{
get { return TextBoxMode.MultiLine; }
set { }
}
protected override void OnPreRender(EventArgs e)
{
if (TextMode == TextBoxMode.MultiLine && MaxLength != 0)
{
Attributes["maxlength"] = MaxLength.ToString();
}
base.OnPreRender(e);
}
}
MaxLength is now supported as of .NET 4.7.2, so as long as you upgrade your project to .NET 4.7.2 or above, it will work automatically.
You can see this in the release notes here - specifically:
Enable ASP.NET developers to specify MaxLength attribute for Multiline asp:TextBox. [449020, System.Web.dll, Bug]
This is absolutely working:
use textarea and value
<div class="form-group row">
<label class="col-md-4 col-form-label">Description</label>
<textarea id="txtDescription" class="form-control" style="height: 40px ; width :250px; " runat="server" maxlength="500" tabindex="32" ></textarea>
</div>
</div>
In code:
While saving:-
BusinessLayer.Description = txtDescription.Value.ToString();
While taking back the value :-
txtDescription.Value = BusinessLayer.Description.ToString();
Important points:
Don't forget to use runat="server"
Don't forget to use value while converting

Getting control id within javascript

I have created my own code to provide date masking and validation for TextBox control in asp.net. Below is the code. The code works perfectly.
function IsValidDate(ctrlID)
{
var validDate=true;
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var mm=myT.value.substring(0,2);
var dd=myT.value.substring(5,3);
var yy=myT.value.substring(6);
if(mm!=0 && mm>12){
myT.value=""; validDate=false;
}
else
{
if((yy % 4 == 0 && yy % 100 != 0) || yy % 400 == 0)
{
if(mm==2 && dd>29){
myT.value=""; validDate=false;
}
}
else
{
if(mm==2 && dd>28){
myT.value=""; validDate=false;
}
else
{
if(dd!=0 && dd>31){
myT.value=""; validDate=false;
}
else
{
if((mm==4 || mm==6 || mm==9 || mm==11) && (dd!=0 && dd>30)){
myT.value=""; validDate=false;
}
}
}
}
}
if(validDate==false)
{
myT.style.backgroundColor='#FF0000';
myT.focus;
}
else
myT.style.backgroundColor='#FFFFFF';
}
function maskDate(ctrlID)
{
var myT=document.getElementById("ctl00_ContentPlaceHolder1_CandidateResume1_TabContainer1_TabPanel2_Education1_"+ctrlID);
var KeyID = (window.event) ? window.event.keyCode : 0;
if((KeyID>=48 && KeyID<=57) || KeyID==8)
{
if(KeyID==8)
return;
if(myT.value.length==2)
{
myT.value=myT.value+"/";
}
if(myT.value.length==5)
{
myT.value=myT.value+"/";
}
}
else
{
window.event.keyCode=0;
}
}
The problem -
I am attaching these functions to the textbox as -
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
TextBox1.Attributes.Add("onKeyPress","maskDate('TextBox1');");
If you look at the javascript code I have collected the control id in myT variable. I have also passed the id of textbox while attaching the js functions using Attributes.Add()
My problem is that i dont want to pass the id of the textbox as i am already attaching it. That is i want to write the code as
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
TextBox1.Attributes.Add("onKeyPress","maskDate();");
My question is how can i get the id of textbox to which i have attached these functions witin JS code.
NOTE: I DONT WANT TO PASS CONTROL NAME OR CONTROLS CLIENTID WHILE ADDING ATTRIBUTES. PLEASE NOTE THAT I WANT TO REPLACE
TextBox1.Attributes.Add("onFocusout","IsValidDate('TextBox1');");
WITH
TextBox1.Attributes.Add("onFocusout","IsValidDate();");
I WANT TO ATTACH THESE FUNCTIONS WITH MULTIPLE TEXTBOXES.
AS I AM USING .Attributes.Add(...) I WANT TO GET THE SAME CONTROLS CLIENTID WITHIN JS CODE.
Your help is highly appreciated.
Thanks and Regards
Mohammad Irfan
var txtControl = document.getElementById("<%= txtControl.ClientID %>");
Control.ClientID
Either pass TextBox1.ClientID to the function, or change the function call to be IsValidDate(this.id). But as you don't want to pass these in, you can place the TextBox1.ClientID in your javascript or use jquery to find it using $('[id*=TextBox1]').

Resources