enter key to insert newline in asp.net multiline textbox control - asp.net

I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P
I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.

It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm_FireDefatultButton function as described here:
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (event.keyCode == 13 &&
!(element &&
element.tagName.toLowerCase() == "textarea"))
{
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;
}

I created a sample page with a TextBox and a Button and it worked fine for me:
<asp:TextBox runat="server" ID="textbox1" TextMode="MultiLine" />
<br />
<br />
<asp:Button runat="server" ID="button1" Text="Button 1" onclick="button1_Click" />
So it most likely depends on either some other property you have set, or some other control on the form.
Edit: TextChanged event is only triggered when the TextBox loses focus, so that can't be the issue.

I can't find that "WebForm_FireDefaultButton" javascript anywhere, is it something asp.net is generating?
Yes.
That's generated to support the DefaultButton functionality of the form and/or Panel containing your controls. This is the source for it:
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (!src || (src.tagName.toLowerCase() != "textarea")) {
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;
}

I suspect it's (like you say) some custom javascript code.
The original asp.net control works fine... you are going to have to check the code

Are you handling the textchanged event for the textbox? That would mean ASP.Net sets the textbox to cause a postback (submit the page) for anything the might cause the textbox to lose focus, including the enter key.

#dave-ward, I just dug through mounds of javascript. most was ASP.NET generated stuff for validation and AJAX, there's a bunch starting with "WebForm_" that I guess is standard stuff to do the defaultbutton, etc. the only javascript we put on the page is for toggling visibility and doing some custom validation...
edit: I did find the below. I don't understand it though :P the beginning of the form the textarea is in, and a script found later: (note, something on stackoverflow is messing with the underscores)
<form name="Form1" method="post" action="default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="Form1">
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['Form1'];
if (!theForm) {
theForm = document.Form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>

http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html worked for me.

this worked for me
<asp:TextBox ID="emailTo" TextMode="MultiLine" Rows="5" Columns="25" Wrap="true" Style="white-space:normal" runat="server"></asp:TextBox>

you can use \n for enter key
i.e.
[a-zA-Z 0-9/.\n]{20,500}

Related

Prevent double clicking asp.net button

I realise this question has been asked but none of the answers worked for my project.
I have a button that when clicked calls an API, so there is a 1 second delay.
I have tried several things nothing works.
btnSave.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
Even that does nothing.
Prevent Double Click .Please add below code in your aspx page.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) { var oControl = args.get_postBackElement(); oControl.disabled = true; }
</script>
This solution is simple and effective. On your button include this code:
OnClientClick="return CheckDouble();"
And wherever you want your JavaScript - e.g. At the bottom of your page:
<script type="text/javascript">
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('This sometimes takes a few seconds - please be patient.');
return false;
}
}
</script>
Most of the above suggestions failed to work for me. The one that did work was the following by tezzo:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
Simpler still, rather than using the above in the code-behind, just use the following:
<asp:Button ID="btnSave" runat="server" Text="Save"
UseSubmitBehavior="false"
OnClientClick="this.disabled='true';"
</asp:button>
UseSubmitBehavior="false" is the key.
You can prevent double-clicking using this code:
Me.btnSave.Attributes.Add("onclick", "this.disabled=true;")
Me.btnSave.UseSubmitBehavior = False
So you can use btnSave_Click to call your API.
Usually I have a lot of Validators in my Page: setting Validator.SetFocusOnError = True I can run this code to reenable save button if a validation failed.
Me.YourControl.Attributes.Add("onfocus", Me.btnSave.ClientID & ".removeAttribute('disabled');")
This is the one I found works in all cases.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
<asp:Button ID="Button2" runat="server" Text="Button2" />
</form>
Now here’s the short JavaScript snippet that will disable the button as soon as it is clicked so that when PostBack occurs the button cannot be clicked again.
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
The above script disables the ASP.Net Button as soon as the page is ready to do a PostBack or the ASP.Net form is submitted.
But in cases you might want to disable all Buttons and Submit Buttons on the page hence for such cases I have created another function which disables all Buttons and Submit buttons whenever there’s a PostBack or form submission
<script type = "text/javascript">
function DisableButtons() {
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].type == "button" || inputs[i].type == "submit") {
inputs[i].disabled = true;
}
}
}
window.onbeforeunload = DisableButtons;
</script>
Prevent Double Click .Please add below code in your aspx page
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
At first my solution is like this:
<script>
function disableButton(btn) {
setTimeout(function () { btn.disabled = true; }, 20);
return true;
}
</script>
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" OnClientClick="return disableButton(this);" />
Without setTimeout the button will be immediately disabled and then the OnClick event will not be fired. The drawback of this approach is that the Save button will not be accessible anymore if some validation fails or some error happens.
So I don't think disable the button is a good solution, and come up with another solution:
function disableButton(btn) {
if (btn.hasclicked) return false;
btn.hasclicked = 1;
btn.onmouseenter = function () { this.hasclicked = 0; };
return true;
}
But my colleague points out that if the post processing is very slow, before it is finished, the user is still able to perform the double postback by leave-enter-click the button. So I figured out another two solutions:
Run the validation from client before submitting the form. But if your page contains multiple ValidationGroup, it is said that the following Page_ClientValidate() should be called multiple times with a passed-in ValidationGroup parameter: e.g. Page_ClientValidate("group1"):
function disableButton(btn) {
if (Page_ClientValidate) {
Page_ClientValidate();
if (!Page_IsValid) {
btn.setAttribute("btnClicked", "n");
return true;
}
}
if (btn.getAttribute("btnClicked") == "y") {
return false;
} else {
btn.setAttribute("btnClicked", "y");
return true;
}
}
As the ASP.NET has only one form in a page (not ASP.NET MVC), we can also let the onsubmit client event of the form to intercept the double click:
function disableButton(btn) {
$("form").submit(function () {
if (btn.getAttribute("btnClicked") == "y")
return false;
else
btn.setAttribute("btnClicked", "y");
return true;
});}
I'll ask QA to test those two approaches(Post edit: QA has proved that it is very dangerous to use this approach. Please refer to my following comments for details).
Try this way, it's a working solution:
For all browsers including Opera Mobile browser which doesn't support js, means your form will not be blocked in that type of browsers.
Add this in Page_load() method:
BtnID.Attributes.Add("onclick", "if(typeof (Page_ClientValidate) === 'function' && !Page_ClientValidate()){return false;} this.disabled = true;this.value = 'Working...';" + ClientScript.GetPostBackEventReference(BtnID, null) + ";");

How do I highlight a textbox border red when it is required?

What property do I use on the required field validator control to make the textbox red if there is a validation error?
Here is my code:
<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" Text="First Name:" CssClass="reg-labels" />
<br />
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60" CssClass="standard_width"/>
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
ASP.Net web forms internally uses a Javascript frameworka located at aspnet_client\{0}\{1} folder to handle the validation, etc. They are basically determined from the property ClientScriptsLocation
Try overriding the default framework function by keeping it in your page includes additional line to set the control_to_validate color
document.getElmentById(val.controltovalidate).style.border='1px solid red';
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60"
CssClass="standard_width" />
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
<asp:Button Text="Super" ID="btnSubmit" CausesValidation="true" runat="server" />
JS
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
if (val.isvalid) {
document.getElementById(val.controltovalidate).style.border = '1px solid #333';
}
else {
document.getElementById(val.controltovalidate).style.border = '1px solid red';
}
}
</script>
Without overloading anything, give your <asp:*Validator tags a CssClass="garbage" attribute.
In your style sheet, create
.garbage {
display: none;
}
.garbage[style*=visible] + input,
.garbage[style*=visible] + select,
.garbage[style*=visible] + textarea {
background-color: #ffcccc;
border: 1px solid #ff0000;
}
and any form control immediately preceded by a validator will be highlighted on invalid data.
EDIT:
I've seen a few methods for forcing a redraw in Chrome, including a pure css solution: transform: translateZ(0);
Murali's answer works great, but I rolled a jQuery version for myself if anyone's interested.
Based on the official documentation (https://msdn.microsoft.com/en-us/library/yb52a4x0.aspx), I was able to get each validator and check to see if it isvalid, and if not, use the errormessage property to populate my own notification system (setStatusMessage() is a function I wrote, feel free to use any other type of status message prompt, like alert() or roll your own).
/*
* Validation Catcher - Sean D Kendle - 9/24/2015
* Catch validation events and add to status messages system
*/
$(document).on("submit", function () {
$.each(Page_Validators, function (i, v) {
var strControlToValidateID = v.controltovalidate;
var $controlToValidate = $("#" + strControlToValidateID);
var arrInvalidControls = new Array(); //collection of all invalid field ids for later
if (!v.isvalid) {
$controlToValidate.addClass("error"); //custom error class, optional
$controlToValidate.css("border-color", "#D00"); //manually set border-color per OP's question
$(".error").eq(0).focus(); /*set focus to top-most invalid field on error, or you can use the v.focusOnError property to check if validator has this set (string "t" if true), but I don't want to have to set this every time*/
arrInvalidControls.push(strControlToValidateID); //collect all invalid field ids for later
$(v).addClass("redtext"); //custom class - allows me to make all errors red without having to add a ForeColor property to every validator
setStatusMessage(v.errormessage, "red", -1); // setStatusMessage is a function I wrote, replace with another alert system if desired, or delete this line
} else {
/*the following prevents control being seen as valid if there are two or more validators for the control - example: required field validator, then custom or regex validator (first would be invalid, second would be valid for empty field)*/
if (!$.inArray(strControlToValidateID, arrInvalidControls)) {
$controlToValidate.removeClass("error");
$controlToValidate.css("border-color", "");
} else {
//console.log(strControlToValidateID + " is already invalid.");
}
}
});
});
I hope this helps someone!
Well, to your disappointment there isn't a direct way (cf https://stackoverflow.com/a/5249021/145682)
However, you can make use of a CustomValidator. Here is one way to define it:
<asp:TextBox ID="txtbx" runat="server"></asp:TextBox>
<asp:CustomValidator ID="customValidator"
runat="server" ValidationGroup="submit" ControlToValidate="txtbx"
ClientValidationFunction="foo" ErrorMessage="*"></asp:CustomValidator>
Make note of the ClientValidationFunction. It has to be written as follows:
function foo(sender, e) {
var value = e.Value;
console.log('Value: ', e.Value);
var ctrlid = sender.controltovalidate;
var targetControl = document.getElementById(ctrlid);
if (vowels.indexOf(value[0].toLowerCase()) == -1) {
console.log('true-executed');
e.isValid = false;
targetControl.style.borderColor = 'red';
}
else {
console.log('else-executed');
e.isValid = true;
targetControl.style.borderColor = '';
}
}
The controltovalidate property of sender will give you the id of the control you are looking for; in other words, your ControlToValidate. And, Value property of e should give you the target control's value.
The other option, is you can write your own server control to do the job: http://msdn.microsoft.com/en-us/library/aa719624(v=vs.71).aspx
Murali's answer worked for me as data changes, but on postback all the fields rendered as though there were no validation errors. I found that ASP.NET lazy-loads ValidatorUpdateDisplay, so the client-side override doesn't take effect until after it's already passed its onload validation. I'm guessing there's either a version or an implementation difference that blocked me here, but other solutions (including a few with CSS) weren't working either.
Eventually, I came upon a solution that combines Murali's answer with Dillie-O's solution from here: Change Text Box Color using Required Field Validator. No Extender Controls Please
<div class="pad-left">
<asp:CompareValidator ID="comvIncTaxable" runat="server" ControlToValidate="tbIncTaxable" Display="Dynamic" Operator="DataTypeCheck" Type="Currency" CssClass="red-border"
ErrorMessage="Please enter a currency value.">
<span></span>
</asp:CompareValidator>
<asp:TextBox runat="server" ID="tbIncTaxable"></asp:TextBox>
</div>
<script type="text/javascript">
$(function () {
setValidatedBordersOnLoad();
});
function ValidatorUpdateDisplay(val) {
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
if (val.className == 'red-border' && val.controltovalidate) {
if (val.isvalid) {
document.getElementById(val.controltovalidate).style.border = '1px solid #ccc';
}
else {
document.getElementById(val.controltovalidate).style.border = '1px solid red';
}
}
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
function setValidatedBordersOnLoad()
{
for (var i = 0; i < Page_Validators.length; i++)
{
var val = Page_Validators[i];
if (val.className == 'red-border' && val.controltovalidate) {
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null) {
if (!val.isvalid)
ctrl.style.border = '1px solid red';
else
ctrl.style.border = '1px solid #ccc';
}
}
}
}
</script>
The nice thing about this solution is it lets you cherry-pick which validators get this special handling simply by adding CssClass='red-border' to the validator. In my case, I only wanted this behavior on fields within a specific grid where cell positioning shouldn't change, but still wanted to use out-of-box functionality elsewhere on the form.

I want to disable a button when asp RequiredFieldValidator shows error

I want to disable the form submit button when asp:RequiredFieldValidator shows error
please advise
if(Page_ClientValidate("SomeValidationGroup") == false)
document.getElementById("button1").disabled = true;
You could use this javascripot function onchange of the control which triggers validation:
<asp:TextBox id="TextBox1" runat=server OnChange="txtValidate();" />
<asp:RequiredFieldValidator id="validator1" runat="server"
ControlToValidate="TextBox1" ...>
<script>
function txtValidate() {
// trigger validation from clientside
var val = <%= validator1.ClientID %>;
if (val.isvalid == false) {
document.getElementById('btnSubmit').disabled = true;
}
}
</script>
Perhaps you can try something like this:
function WebForm_OnSubmit() {
if (typeof (ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) {
//disable button here
return false;
}
//enable button here
return true;
}
For more information about this function visit and understanding the ASP.NET Validation Library visit this post.
Alternatively, as #Nag suggested, a custom validator may also be able to accomplish this as you are able to define the client side JavaScript.
You should use validationgroup + requirevalidation then the button should not be clickable

Display confirmation box in ASP.NET using JavaScript

I need to show the confirm box "Are you sure You Want To continue?" If "Yes" I need the ASP.NET textbox value to be cleared out. Otherwise it should not be cleared.
function doConfirm(){
if (confirm("Are you sure you want to continue?")){
var mytxtbox = document.getElementById('<% =myAspTextBox.ClientID %>');
mytxtbox.value = '';
}
}
Note the myAspTextBox refers to the name of the asp:textbox controls ID property
<asp:textbox ID="myAspTextBox" runat="server" OnClientClick="javascript:doConfirm();"
Hope this helps
In your asp textbox tag add this:
OnClientClick="javascript:testDeleteValue();"
...
And add this script:
<script>
function testDeleteValue()
{
if (window.confirm('Are you sure You Want To continue?'))
document.getElementById("<%=<th id of your textbox>.ClientID%>").value = '';
}
</script>
If you want this to happen on click of your radio box, put it in this tag and just replace onclientclick with onclick.
<input type='radio' onclick='testDeleteValue()'/>
If you download the AjaxControlToolkit you can use the ConfirmButtonExtender to display a simple confirmation box to a user after a button is clicked to proceed with the action or cancel
You can see here for an example and here for a tutorial on how to implement this
Okay I just noticed the bit about radio buttons, in any case the AjaxControlToolkit is a good place to start if you want to implement JavaScript solutions in .Net projects
if this is your textbox markup:
<asp:textbox id="txtInput" runat="server" />
and then this is the button that will trigger the confirm:
<asp:button id="btnSumbit" runat="server" onclientclick="return clearOnConfirm();" text="Submit" />
then you'll need the following javascript:
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
return true;
} else {
return false;
}
}
</script>
If all you want to do is to clear the textbox but always continue with the postback then you don't ever need to return false as above but always return true as below. In this scenario you should rethink the message you display to the user.
<script type="text/javascript">
function clearOnConfirm() {
if (confirm("Are you sure you want to continue?")) {
document.getElementById("<%=txtInput.ClientID %>").value = '';
}
return true;
}
</script>
function stopTimer() {
if (window.confirm('Are you sure You Want To continue?')) {
$find('Timer1')._stopTimer()
return true;
}
else {
return false;
}
<asp:Button ID="Btn_Finish" runat="server" Text="Finish" Width="113px" OnClick="Btn_Finish_Click" OnClientClick="return stopTimer();" Height="35px"
protected void Btn_Finish_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
// if any functions to be done eg: function1();
Response.Redirect("~/Default2.aspx");
}
There is also a timer stop doing in the function. The confirmation box if press "Ok" timer stops and also its redirected to new page "Default2.aspx"
else if chosen cancel then nothing happens.

Link Button on the page and set it as default button, work fine in IE but not in Mozila

I have a link button on the page and set it as default button, It works fine in IE but not working in Mozila Firefox. Does anybody have any clue how to resolve this issue?
The DefaultButton property is not supported for use with a LinkButton. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx
The easiest solution is to include a dummy Button on your page with style="display:none", set that as the defaultbutton and give it the same event handlers as your LinkButton.
I had this kind of issue with FF3 and ASP.NET linkbuttons. This seems to be a bug with FF3 (not sure), but the script that fixed is given below:
var __defaultFired = false;
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
var defaultButton;
if (__nonMSDOMBrowser)
defaultButton = document.getElementById(target);
else
defaultButton = document.all[target];
if (defaultButton) {
if(typeof(defaultButton.click) != "undefined")
defaultButton.click();
else
eval(unescape(defaultButton.href.replace("javascript:", "")));
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
Keep it at the end of the page so that it overrides the WebForm_FireDefaultButton method rendered by ASP.NET.
My first Stack Overflow write, wow :-)
asp.net:
<asp:Panel runat="server" DefaultButton="lbHello">
First name: <asp:TextBox runat="server" ID="txtFirstName" />
<asp:LinkButton ID="lbHello" Cssclass="button" runat="server" Text="Click me" OnClick="lbHello_Click" />
</asp:Panel>
js:
$(document).ready(function () { $('.button').eventClick(); });
$.fn.eventClick = function() {
function eventClick(a) {
if (a && typeof (a.click) == 'undefined') {
a.click = function () {
var result = true;
if (a.onclick) result = a.onclick();
if (typeof (result) == 'undefined' || result) {
eval(a.getAttribute('href'));
}
}
}
}
return eventClick($(this).get(0));
}
work only first time we press enter in textbox. After adding some text in textbox and then pressing enter ,default button will not fire.
I think its very simple, just add onkeypress js event of textbox where post back is required.
txtUserName.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13)
__doPostBack('" + btnLogin.UniqueID + "','')");
hope this will be helpful.

Resources