Select text of the control when validation occurs - javascript

I want to highlight text in control when validation occurs.
How can I achieve this?
<script language="javascript" type="text/javascript">
function changeColor(source, args) {
var txt = document.getElementById('<%= txtAge.ClientID %>');
if (args.Value.length >= 3) {
txt.style.background = '#66CCFF';
args.IsValid = false;
}
else {
txt.style.background = 'none';
args.IsValid = true;
}
}
</script>
<asp:TextBox ID="txtAge" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfldtxtAge" ErrorMessage="enter the value" ControlToValidate="txtAge" runat="server" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="ctmtxtAge" runat="server" ClientValidationFunction="changeColor" ControlToValidate="txtAge" ErrorMessage="CustomValidator1" ></asp:CustomValidator>
I use this code for highlighting background of control, but I need to highlight the text of control.
Please help me.

Please use
txt.select();
instead of
txt.style.background = '#66CCFF';
please let me know if this does not work.

txt.style.color= '#66CCFF' instead of txt.style.background = '#66CCFF';
use this thing to change the color of the text

Related

Validation for my ASP textboxes is not working using javascript and ASP.NET

I just want to ask why my form validation for my asp textboxes is not working. It should be like when the user does not input a text in the textbox, a description in the paragraph tag will display to please input a text. But it is not working.Please help me on solving this.
Here is the javascript code:
function checkForm() {
var errors = [];
if ($("#itemBrand").value == "") {
errors[0] = "Please input a text!";
}
if ($("#itemModel").value == "") {
errors[1] = "Please input a text!";
}
if (errors.length > 0) {
if (errors[0] != null) {
document.getElementById("itemBrandValidate").innerHTML = errors[0];
}
if (errors[1] != null) {
document.getElementById("itemModelValidate").innerHTML = errors[1];
}
return false;
}
return true;
}
And here is the aspx:
<asp:TextBox ID="itemBrand" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemBrandValidate"></p>
<asp:TextBox ID="itemModel" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox><br />
<p id="itemModelValidate"></p>
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click" OnClientClick="return checkForm()"/>
Add ClientIdMode = "Static" on your textboxes. Otherwise the .NET platform generates an Id which is not the same as the server ID property and your Jquery selector is not working as expected.
For example:
<asp:TextBox ID="itemBrand" ClientIDMode="static" runat="server" BackColor="#FFFF66"
BorderColor="Black" BorderWidth="1px" Height="20px" Width="300px">
</asp:TextBox>
Client side id of asp.net server controls is different from server side id.
You may use ClientIDMode = "Static" (introduced in .NET 4.0) or you might use ClientID as shown below , also I've tried to re-write your validation function a bit.
function checkForm() {
var success = true;
var itemBrandID = "<%= itemBrand.ClientID %>" ;
if ($("#" + itemBrandID).value == "") {
success = false;
document.getElementById("<%= itemBrandValidate.ClientID %>").innerHTML = "Please input a text!";
}
var itemModelID = "<%= itemModel.ClientID %>" ;
if ($("#" + itemModelID).value == "") {
success = false;
document.getElementById("<%= itemModelValidate.ClientID %>").innerHTML = "Please input a text!";
}
return success;
}
Also suggest you to read this excellent post by Rick Strahl on A generic way to find ASP.NET ClientIDs with jQuery
Hope this helps !

How to make asp textbox empty by JavaScript

I have got a problem with making textbox empty using JavaScript function.
If checkbox is unchecked the asp:Textbox should make disabled and empty.
It happens, but in code behind all the time is visible previous value which was entered before in that textbox.
<asp:RadioButton ID="radio_fx_no" runat="server" Text="NO" GroupName="optradio1" onclick="CheckBoxChangedDisableFx(this);" />
<asp:RadioButton ID="radio_fx" runat="server" Text="YES" GroupName="optradio1" onclick="CheckBoxChangedAbleFx(this);" />
<asp:TextBox ID="txt_fx" ClientIDMode="Static" runat="server" Enabled="false" />
<script>
function CheckBoxChangedAbleFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').disabled = false;
}
}
function CheckBoxChangedDisableFx(checkbox) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = true;
}
}
</script>
Any ideas what is wrong in my code?
This problem is called the Cacheing the browser data. You can try three things in this case:
1) Clear value of textbox in pageload event at every postback:
if (IsPostBack)
{
txt_fx.text = "";
}
and in your aspx code make text="":
<asp:TextBox ID="txt_fx" Text="".../>
2) Set AutoComplete property of textbox to off for html input
or disable autocompletetype property of asp textbox
<asp:TextBox ID="txt_fx" autocompletetype="disabled".../>
3) or Set AutoComplete of your FORM tag of your page to "off"
If you want to clear actual value of textbox on server side without postback then you need to use AJAX.
Hope it will help you..!!
in .cs file,Page_Load method,plus such code:
if(!Page.IsPostBack)
{
radio_fx.Attributes.Add("onClick", "return CheckBoxChangedState(this,false);");
radio_fx_no.Attributes.Add("onClick", "return CheckBoxChangedState(this,true);");
}
and in .aspx file,change as follows:
<script type="text/javascript">
function CheckBoxChangedState(checkbox, state) {
if (checkbox.checked == true) {
document.getElementById('<%= txt_fx.ClientID %>').value = "";
document.getElementById('<%= txt_fx.ClientID %>').disabled = state;
}
}
<asp:RadioButton ID="radio_fx_no" runat="server" AutoPostBack="false" Text="NO" GroupName="optradio1" />
<asp:RadioButton ID="radio_fx" runat="server" AutoPostBack="false" Text="YES" GroupName="optradio1" />

Update one textbox using javascript function when another changes

I have a javascript function that counts characters in 2 different textboxes and puts the value in a third textbox.
This is the function is as follows:
function CountChars() {
var subjectLength = document.getElementById("txtBoxSubject").value.length;
var msgLength = document.getElementById("txtBoxMsg").value.length;
document.getElementById("txtBoxCnt").value = subjectLength + msgLength;
}
I call it from the Message text box using 'onkeyup' and it works fine.
<asp:TextBox ID="txtBoxMsg" runat="server" ClientIDMode="Static"
TextMode="MultiLine" onkeyup="CountChars()"></asp:TextBox>
The Subject textbox can be changed using a dropdown list or a user adding text to it. So using 'onkeyup' will not work for the Subject textbox. I tried using 'onchange' and nothing is entered in the Count text box.
This is the Subject html:
<asp:TextBox ID="txtBoxSubject" runat="server" ClientIDMode="Static" onchange="CountChars()"></asp:TextBox>
What am I doing wrong?
How can I call the javascript function whenver the text changes in the Subject textbox?
Thanks.
UPDATE
This is the Subject dropdown and the function that is called when it changes.
<asp:DropDownList ID="ddListSubject" runat="server" ClientIDMode="Static" AutoPostBack="true" onchange="SubjectChanged();">
</asp:DropDownList>
function SubjectChanged() {
var strSubject = document.getElementById("ddListSubject").value;
if (strSubject == "Custom") {
document.getElementById("txtBoxSubject").value = "";
document.getElementById("txtBoxSubject").focus();
}
else {
document.getElementById("txtBoxSubject").value = strSubject;
}
CountChars(); //number appears for a second then disappears
}
it seems like you not terminating the function with semi column. use something like onkeyup="CountChars();"
Your .aspx are using MasterPage? The names of Asp.Net objects changing in the rendered page. Try using <% =% Objeto.ClientID>.
function CountChars() {
var subjectLength = document.getElementById("<%=txtBoxSubject.ClientID %>").value.length;
var msgLength = document.getElementById("<%= txtBoxMsg.ClientID %>").value.length;
document.getElementById("<%= txtBoxCnt.ClientID %>").value = subjectLength + msgLength;
}
Or maybe use JQuery. Look at the code below, works as you described.
Subject:
<input id="text1" type="text" />
<br />
Msg
<input id="text2" type="text" multiple style="height: 100px" />
<br />
Total: <span id="total">0</span>
<script type="text/javascript">
$(document).ready(function () {
$("input[type=text]").keyup(function () {
var total = 0;
$("input[type=text]").each(function () {
total += $(this).val().length;
});
$("#total").html(total);
});
});
</script>
Hope this helps you
Dummy me...I removed the AutoPostBack="true" from the Dropdown!
Thanks for all of your help!!

unable to set asp.net textbox value in javascript

I'm trying to create a simple counter box next to an ASP.NET multi-line textbox. I'm using JavaScript to do this ClientSide.
<script type="text/javascript">
function textCounter(maxlimit) {
var txtField = document.getElementById('<%=txtWhatCompanyDoes.ClientId%>')
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
My page code is;
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter('txtWhatCompanyDoes', 'txtWhatCompDoesChrsRem',2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<asp:TextBox ID="txtWhatCompDoesChrsRem" runat="server"></asp:TextBox>
The problem is that it works right up to the last line of the JavaScript as I can use an alert to tell me the number of characters left, but's just not writing the value to the textbox. Am I doing something wrong?
Try adding client id on line 4 at the end of txtWhatCompDoesChrsRem
function textCounter(maxlimit) {
var txtField = document.getElementById('<%=txtWhatCompanyDoes.ClientId%>')
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem.ClientId%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
Wow, how emabarassing. I can't believe I missed that. Can I be cheeky and ask how this can be made dynamic for multiple counter boxes on one page e.g.
<script type="text/javascript">
function textCounter(field, cntField, maxlimit) {
var txtField = document.getElementById(field)
var cntCounter = document.getElementById('<%=txtWhatCompDoesChrsRem.Clientid%>')
if (txtField.value.length > maxlimit) {
txtField.value = txtField.value.substring(0, maxlimit);
}
else
{
var chrsleft = maxlimit - txtField.value.length;
cntCounter.value = chrsleft;
}
}
</script>
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter(this.id, txtWhatCompDoesChrsRem',2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<asp:TextBox ID="txtWhatCompDoesChrsRem" runat="server"></asp:TextBox>
I can pass the first control id using "this.id" but how can I pass the counter box as a variable?
This only way I could solve this was to set the counter box as an rather than an ASP textbox.
<asp:TextBox ID="txtWhatCompanyDoes" onKeyUp="textCounter(this.id, this.form.txtWhatCompDoesChrsRem, 2000);" runat="server" TextMode="MultiLine" Rows="10"></asp:TextBox>
<input name="txtWhatCompDoesChrsRem" type="text" value="2000" />
every element in asp.net have inherit id like "txtWhatCompDoesChrsRem.Clientid"
so when u want to use some element in java script u can simply add one line to the element :
<asp:TextBox id="txt1" ClientID="static" ...
thats mean u can use the element directly by his name
java script :
var txtField = document.getElementById("txt1")

Validating Textbox with CustomValidator's ClientValidationFunction not firing

I am having some serious issues with this. I have a two fields like this, both of them being assigned datepickers with jquery.
<asp:TextBox ID="RTRP" runat="server" CssClass="textEntry" Width="120"></asp:TextBox>
<asp:CustomValidator runat="server" ID="CustomValidator3"
ControlToValidate="RTRP"
Text="No date selected"
ValidateEmptyText="True"
ClientValidationFunction="clientValidate"
Display="Static">
</asp:CustomValidator>
<asp:TextBox ID="ContEd" runat="server" CssClass="textEntry" Width="120"></asp:TextBox>
<asp:CustomValidator runat="server" ID="CustomValidator1"
ControlToValidate="ContEd"
Text="No date selected"
ValidateEmptyText="True"
ClientValidationFunction="clientValidate"
Display="Static">
</asp:CustomValidator>
With the following javascript to validate it.
$("#<%=RTRP.ClientID %>").datepicker();
$("#<%=ContEd.ClientID %>").datepicker();
function clientValidate(sender, args) {
args.IsValid = args.Value.length > 0;
}
Both get their datepickers, but the validation function simply refuses to be fired and always allows the form to submit. I am completely lost here, what am I doing wrong?
You are checking if a string's length is less than 0 (what is never true) here:
function clientValidate(sender, args) {
if (args.Value.length < 0) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
I'm not sure if this is what you want(you could simpy use a RequiredFieldValidator), but...
function clientValidate(sender, args) {
args.IsValid = args.Value.length > 0;
}
If you assign $.datepicker() behaviour to any text, and run page.. you will find that textbox on which you override jQuery datepicker had css set display : none.. so that might be the reason that custom validation not getting for that textbox...
why dont you use
<asp:RequiredFieldValidator id="id" controltovalidate="controlname" erormessage="please enter the dates">
</asp:RequiredFieldValidator>
correct me i am wrong
Change you method to this.and try again
function clientValidate(sender, args)
{
if(Page_ClientValidate())
{
if (args.Value.length < 0)
{
args.IsValid = false;
} else
{
args.IsValid = true;
}
}
}

Categories

Resources