Display Dialog Box When User Meets MaxLength of TextBox - c#

I have a asp.net C# application. I have a TextBox that has a MaxLength set of 3000. When the user reaches the maxlength of 3000 I want a JavaScript dialog box to open and alter the user of this. I can't figure out how to do it. Can anyone help me? Thanks.

From aspdotnet-suresh:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Limit the number of characters in textbox or textarea</title>
<script type="text/javascript">
function LimtCharacters(txtMsg, CharLength, indicator)
{
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength)
{
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
</script>
</head>
<body>
<div style="font-family:Verdana; font-size:13px">
Number of Characters Left:
<label id="lblcount" style="background-color:#E2EEF1;color:Red;font-weight:bold;">3000</label><br/>
<textarea id="mytextbox" rows="5" cols="25" onkeyup="LimtCharacters(this,3000,'lblcount');"></textarea>
</div>
</body>
</html>

You can use the TextChanged event of your TextBox for this. Inside your handler, you can simply check the length of the TextBox.Text property, and display a MessageBox if it reaches the maximum length like so:
Response.Write(string.Format("<script>alert('{0}');</script>", message));

You can restrict the number of characters with this JavaScript
<script language="javascript" type="text/javascript">
function limitText(Field, limitNum) {
if (Field.value.length > limitNum) {
Field.value = Field.value.substring(0, limitNum);
}
}
</script>
<asp:FormView runat="server">
<ItemTemplate>
<b>Something</b>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onKeyDown="limitText(this,3000);"
onKeyUp="limitText(this,3000);"></asp:TextBox>
</EditItemTemplate>
</asp:FormView>
Or to Display alert,
<input type="text" onkeydown="return testLength()" id="txtBox" />
function testLength(){
var e = document.getElementById('txtBox');
if(e.value.length>6)
{
alert('you have entered more than 3000 characters');
// Set value back to the first 6 characters
e.value = e.value.substring(0, 3000);
}
return true;
}

Related

asp:textbox select all text by click button and copy to client clipboard

Is there any way to select all text within a multiline asp:textbox and copy it to client clipboard by clicking a button, using c#?
Thank you in advance.
You can use document.execCommand("copy"); just be aware that this is supported by new browsers mostly and as far as I know there is no support for Safari:
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCopy").click(function () {
var id = "#" + "<%= txtText.ClientID %>";
try {
$(id).select();
document.execCommand("copy");
}
catch (e) {
alert('Copy operation failed');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtText" runat="server" Text="Some sample text to copy"></asp:TextBox>
<button id="btnCopy">Copy</button>
</form>
</body>
Tested and works with the following browsers:
IE 11 and up
Google Chrome 51.0.2704.84
Firefox 43.0.1
I think #Denis Wessels answer was great but used plain textarea instead of asp:TextBox, therefore I want to write my own that includes asp:TextBox control.
Consider you have a multi-line text area with asp:TextBox server control and a button to copy content into clipboard:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine">
<button id="copy">Copy to Clipboard</button>
Use jQuery and a JS function similar to this:
<script type="text/javascript">
$(document).ready(function () {
$("#copy").click(function() {
// use ASP .NET ClientID if you don't sure
// for ASP .NET 4.0 and above, set your ClientID with static mode
var textarea = "<%= TextArea.ClientID %>";
$(textarea).select();
$(textarea).focus(); // set focus to this element first
copyToClipboard(document.getElementById(textarea));
});
});
function copyToClipboard(elem)
{
var result;
var target = elem;
startPoint = elem.selectionStart;
endPoint = elem.selectionEnd;
var currentFocus = document.activeElement;
target.setSelectionRange(0, target.value.length);
try
{
// this may won't work on Safari
result = document.execCommand("copy");
}
catch (e)
{
return alert("Copy to clipboard failed: " + e);
}
// returning original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
elem.setSelectionRange(startPoint, endPoint);
return result;
}
</script>
Reference with minor changes: https://stackoverflow.com/a/22581382, https://stackoverflow.com/a/30905277
Note that for ASP .NET 4 and above you can set static ClientID:
<asp:TextBox ID="TextArea" runat="server" TextMode="MultiLine" ClientID="TextArea" ClientIDMode="Static">
thus you can use $("#TextArea") directly rather than $("<%= TextArea.ClientID %>").
You can use this class:
System.Windows.Forms.Clipboard.SetText(..) <= Sets the text to clipboard,
Inside SetText(), you put textbox.Text to get the text from the multiline asp.net textbox.
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<center>
<p id="p1">Hello, I'm TEXT 1</p>
<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input type="text" id="" placeholder="TEST it here;)" />
</center>

Check All Checkboxs feature Asp.net

I basically want to ask this question(How to implement "select all" check box in HTML?) but from a asp.net point of view. There seems to be more challenges to over come when you are using asp.net to do this. The CssClass attribute generates a span container with the class you specified and it doesn't get placed on the input. Along with the challenge of masterpages and controls. I am looping through records and displaying them with a checkbox. I was hoping to grab all the checkboxes by class to perform the check all. I don't think that will be possible. Any advice?
Markup:
<asp:CheckBox runat="server" ID="checkAll" CssClass="CheckAll" />
<asp:Table ID="tblitems" Visible="false" Width="80%" HorizontalAlign="Center" runat="server">
<asp:TableRow>
//The data gets added as a table row.
</asp:TableRow>
</asp:Table>`
Browser:
//Check All check box
<span class="CheckAll"><input id="ctl00_ContentPlaceHolder1_checkAll" type="checkbox" name="ctl00$ContentPlaceHolder1$checkAll" /></span>
//Each checkbox that will be checked looks like this
<span class="chkBox"><input id="ctl00_ContentPlaceHolder1_ctl01" type="checkbox" name="ctl00$ContentPlaceHolder1$ctl01" /></span>
JavaScript
$('.CheckAll').click(function (event) {
alert("start");
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
alert("end");
}
});
ClientIDMode property of the checkbox control will allow you to more easily work with client-side selectors, like this:
Markup:
<asp:CheckBox runat="server" ID="checkAll" CssClass="CheckAll" ClientIDMode="Static" />
Check out the Control.ClientIDMode Property MSDN documentation.
Note: ClientIDMode is available in ASP.NET 4.0 and later.
Since each checkbox is in a span with a class 'chkBox', locate the checkboxes using that selector on the click handler:
$('.CheckAll').on('click', function (event) {
var checked = $(this).prop('checked');
$('.chkBox :checkbox').prop('checked', checked);
});
It would be more precise if you wrapped all the checkboxes you'd like to have checked in a container div:
<div id="myCheckboxes">
// .NET code here
</div>
JS:
$('.CheckAll').on('click', function (event) {
var checked = $(this).prop('checked');
$('#myCheckboxes :checkbox').prop('checked', checked);
});
Karl, I believe, has improved the approach. However, if you want to stick with what you have, modify your Javascript to be the following:
$('.CheckAll').find(':checkbox').click(function (event) {
alert("start");
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
alert("end");
}
});
The following code basically selectes all checkboxes, and change the check statuses based on the CheckAll Checkbox.
<script type="text/javascript">
$(document).ready(function () {
$('#<%= CheckAll.ClientID %>').click(function() {
var checkedStatus = this.checked;
$("input[type='checkbox']").attr('checked', checkedStatus);
});
});
</script>
<asp:CheckBox runat="server" ID="CheckAll" />
<asp:CheckBox runat="server" ID="Check1" />
<asp:CheckBox runat="server" ID="Check2" />
<asp:CheckBox runat="server" ID="Check3" />
<asp:CheckBox runat="server" ID="Check4" />
Multiple Group of CheckBoxes in a Single Page
If you have multiple groups of checkboxes in a single page, you can differentiate them with class.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication2012.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
// Selects all enabled checkboxes
$("#<%= CheckAll.ClientID %>").click(function () {
var checkedStatus = this.checked;
$(".myCheckBox input[type='checkbox']").attr('checked', checkedStatus);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox runat="server" ID="CheckAll" Text="Check All" CssClass="myCheckAll" /><br />
<asp:CheckBox runat="server" ID="Check1" Text="Check1" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check2" Text="Check2" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check3" Text="Check3" CssClass="myCheckBox" /><br />
<asp:CheckBox runat="server" ID="Check4" Text="Check4" CssClass="myCheckBox" />
</form>
</body>
</html>
I got it to work using this script below. This not work for every scenario but it worked very well for mine so far. Thanks!
mark up
<asp:CheckBox runat="server" ID="CheckAll" OnClick="toggle(this)" />
Javascript
function toggle(source) {
checkboxes = document.getElementsByTagName('input');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}

"password" text in TextMode="password" in asp:TextBox

I would like to use a TextBox for a password, but before the user enters the TextBox, I want to see "enter password" as the text.
How is this usually accomplished using ASP.NET? Do I have to create second textbox and manipulate the visibility using Javascript?
If using HTML 5, just use a placeholder.
With jQuery, there is the jQuery-watermark plugin:
Capable of displaying a watermark in password input elements, showing the watermark in plain text, but then switching to password-protected (obscured) mode when focused.
You can use the AJAX watermark.
Example can be found here:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
This is how I fixed it mine and works a dream:-
<script type="text/javascript" language="javascript">
function LoginPassword() {
document.getElementById("<%= txtTempBox.ClientID %>").style.display = "none";
document.getElementById("<%= txtPassword.ClientID %>").style.display = "";
document.getElementById("<%= txtPassword.ClientID %>").focus();
}
function LoginPassword1() {
if (document.getElementById("<%= txtPassword.ClientID %>").value == "") {
document.getElementById("<%= txtTempBox.ClientID %>").style.display = "block";
document.getElementById("<%= txtPassword.ClientID %>").style.display = "none";
}
}
<div id="dloginPassword">
<asp:Label ID="hdnLgnPassword" runat="server" Text="Password" Style="display: none;" CssClass="" />
<asp:TextBox ID="txtTempBox" runat="server" Text="Password"
onfocus="LoginPassword();" CssClass="Mainlogintextbox txtWaterMark" />
<asp:TextBox TextMode="Password" ID="txtPassword" runat="server" Style="display: none;"
onblur="LoginPassword1();" CssClass="Mainlogintextbox" />
</div>
Hope this helps?
Cheers
Steve

Restrict single and double quotes in textbox in ASP.NET

I want to restrict sinqles qoutes and double quotes to enter to a Textbox in Asp.net. How can i achieve it? How can i validate the textbox?
Do you use AjaxControlToolkit? if so, then use this.
<asp:TextBox runat="server" ID="TextBox1" Width="100px" />
<cc1:FilteredTextBoxExtender FilterMode="InvalidChars" ID="ftbe_TextBox1" runat="server"
TargetControlID="TextBox1" InvalidChars=""'" />
Where: cc1 is the TagName for AjaxControlToolkit
if not, do it manually
<asp:TextBox runat="server" ID="TextBox1" Width="100px" onkeypress="return restrictQuotes(event);" />
<script type="text/javascript">
function restrictQuotes(evt) {
var keyCode = evt.which ? evt.which : evt.keyCode;
return (keyCode != '"'.charCodeAt() && keyCode != "'".charCodeAt());
}
</script>
I would use javascript to do real-time validation with the textboxes onchange event. Then you can use the string.contains() method on the server-side for server-side validation.
you can add a RegularExpressionValidatorand set the ValidationExpression ='^[^\"]*$' to restrict quotes input
You could do it in javascript
<script type="text/javascript">
function fixit() {
var numberOfElements = document.theForm.elements.length;
for (x=0; x<numberOfElements; x++) {
// replace all the single, double quotes:
var curElement = window.document.theForm.elements[x];
curElement.value = curElement.value.replace(/\'/g, "'");
curElement.value = curElement.value.replace(/\"/g, """);
}
return true;
}
</script>
Then in the form you would write this
<form name='theForm' onSubmit='return fixit()'...
This code would cycle all the elements. If you want to validate a single element you could prevent the user from writing those characters
in the textbox you could do this:
<input type="text" name="foo" onkeypress="return fix(event);">
In javascript:
<script type="text/javascript">
function fix(e)
{
if(e.charCode == 34|| e.charCode == 39)
{
return false;
}
return true;
}
</script>
The last part prevents users from writing quotes and double quotes.

C# Disable/Enable Button based on Empty/Populated Text Boxes

I have a form with 5 text boxes and a button, and when the button is clicked it send the data to a SQL database. I would like the button to be disabled if any of the text boxes are null, how do I do this in C#? (I am in Visual Studio 2010 ASP.NET web app)
You need to write JavaScript/jQuery code.
Yes, What Sam said is right!!
you need to check first whether all your text boxes are empty or not.
that will be done by
If(txtbox1.text == "" || txtbox2.text == "" || txtbox3.text == "" || txtbox4.text == "" || txtbox5.text == "")
If any of the text box is empty then make the button disabled.
button1.enable = false;
If all are filled then make it as enabled.
button1.enable = true;
If you do not want to use Client side scripts, you can use validations for your controls
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1" >
</asp:RequiredFieldValidator>
Validation will trigger on postbacks.
If you have multiple controls, but you do not want to validate them all, you can use Validation Group. Check this link for using Validation Groups
use javascript setInterval on Page load if if you are using this single form on the page and check each textbox value length .. if anyone is null then disable submit button..
use jquery to disable and enable them.. check following code snippet that i have created for sample..
use this to access server control id if you are using these controls inside some container control eg. panel, contentplaceholder etc : $("#<%=button1.ClientID>%>")
$("#text1").val().length will check then length of text in textbox.. and then use jquery to enable and disable them..
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<%-- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js" type="text/javascript"></script>--%>
<%--<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7-vsdoc.js" type="text/javascript"></script>--%>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").attr('disabled', 'disabled');
$("#text1").keypress(function () {
check();
});
var intv = self.setInterval("check()", 1000);
});
function check() {
if ($("#text1").val().length > 0) {
$("#submit").removeAttr('disabled');
}
else {
$("#submit").attr('disabled', 'disabled');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

Categories