unable to set asp.net textbox value in javascript - 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")

Related

how i can check value of "DropDownList" in asp.net with js?

I'm new in asp.net and java script.
i want to check value of asp:dropdownlist' with java script.
selected value define in database but when i select an item with value 9 i didn't get back "hello" alert.any body can help me ? thanks.
<script>
$(document).ready(function offermessage() {
var a = ($('#<%=offermessage.ClientID %> option:selected').val());
if(a==9)
{
alert("hello");
}
});
</script>
<div class="col-12">
<asp:DropDownList ID="offermessage" CssClass="farsi-font drp-down-list" required="" runat="server" >
<asp:ListItem Value="Baseid">value</asp:ListItem>
</asp:DropDownList>
</div>
can you try with the below code
$(document).ready(function(){
function offermessage() {
var a = $('#<%=offermessage.ClientID%>').val();
if(a == 9)
{
alert("hello");
}
}
});
if you want to get the value of the dropdown on change event of dropdown then you can add below code
$(document).ready(function(){
$('#<%=offermessage.ClientID%>').on('change',function(){
var a = $(this).val();
if(a == 9)
{
alert("hello");
}
});
});

Issue in changing textbox background color by using javascript

I want to pass the texttbox id to javascript function and change the color of the textbox if the value is null.
function fnOnUpdateValidatorsNewChangeChange(txtid) {
var txt1 = document.getElementById(txtid);
var Value = document.getElementById(txtid).value
if (Value == "") {
txt1.style.background = "#FFF000";
}
}
<asp:TextBox runat="server" ID="txtlabelID" class="textbox" TextMode="SingleLine"
onchange="fnOnUpdateValidatorsNewChangeChange('<%= txtlabelID.ClientID %>')"
But it's getting Null error.
you not need to pass ID of textbox and find textbox using the same id ..
You just pass this as a textbox in argument for E.g.
<asp:TextBox runat="server" ID="txtlabelID" class="textbox" TextMode="SingleLine"
onchange="fnOnUpdateValidatorsNewChangeChange(this)"
function fnOnUpdateValidatorsNewChangeChange(txtbox) {
if (txtbox.value == "") {
txtbox.style.background = "#FFF000";
}
else
txtbox.style.background = "";
}
Is it more Simple ??

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!!

Ajax autocomplete Extender prevent to type invalid value in text box

am using Ajax AutoCompleteExtender in asp textbox as below.
it's working fine but,
Problem: when user type text which is invalid or not match from the database value, it should show a message to user like "keyword not matched..."
Code
<asp:HiddenField id ="hdnFieldValue" runat="server"/>
<asp:TextBox ID="txtContactsSearch" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="2"
CompletionInterval="100" OnClientItemSelected="ClientItemSelected" UseContextKey="true" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtContactsSearch"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
Java Script Code
<script type="text/javascript">
function ClientItemSelected(sender, e) {
$get(e.get_value());
$get("<%=hdnFieldValue.ClientID %>").value = e.get_value();
}
</script>
I am get value using above javascript method into asp hidden field. But I want to set Empty into hidden field when user type invalid text
Please give me suggestions.
Thanks.
ADD IN YOUR AUTOEXTENDER :
<cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" OnClientPopulated="ClientPopulated"
</cc1:AutoCompleteExtender>
JS : From below you can highlight your Text with result,same way you can check for text
<script type="text/javascript">
function ClientPopulated(source, args) {
if (source._currentPrefix != null) {
var list = source.get_completionList();
var search = source._currentPrefix.toLowerCase();
for (var i = 0; i < list.childNodes.length; i++) {
var text = list.childNodes[i].innerHTML;
var index = text.toLowerCase().indexOf(search);
if (index != -1) {
var value = text.substring(0, index);
</script>

How do I change visibility of an asp label with javascript with an onchange event of an asp textbox

I have the used css to set the display of the label to none
I am very new to js so I'm not 100% on my code for it..
<script type="text/javascript">
function strLen(field, count)
{
var str = document.getElementById("textbox1");
if(str.value.length > 2)
{
document.getElementById("errorLabel").style.display = 'inherit';
}
}
</script>
<asp:textbox id="textbox1" CssClass="style5" runat="server" MaxLength="10" onchange="strLen()"></asp:textbox>
You have arguments in your JS function, but you're not passing any arguments in the onchange event.
Apply the following code to your TextBox:
<asp:TextBox ID="textbox1" CssClass="style5" runat="server" MaxLength="10" onkeyup="strLen(this, 2);"></asp:TextBox>
METHOD #1: Using a Label
Your error label should look like this:
<asp:Label ID="lblError" runat="server" Text="Exceeds max length" style="display:none;"></asp:Label>
And then in your JavaScript function, you can do this:
EDIT: Had logic backwards - changed to: input.value.length > count ? "block" : "none";
strLen = function(input, count){
var errorLabel = document.getElementById("<%=lblError.ClientID%>");
if (errorLabel)
errorLabel.style.display = input.value.length > count ? "block" : "none";
}
METHOD #2: Using a span instead of a Label
Or you could just use a span instead of a label, like this:
<span id="errorLabel" style="display:none;">Exceeds max length</span>
And change the JavaScript function to this:
EDIT: Had logic backwards - changed to: input.value.length > count ? "block" : "none";
strLen = function(input, count){
var errorLabel = document.getElementById("errorLabel");
if (errorLabel)
errorLabel.style.display = input.value.length > count ? "block" : "none";
}
If you are using asp.net 4, then you can set the ClientIdMode of the label to static and reference it like you are. See Rick's post here:
http://www.west-wind.com/weblog/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40
You can use a RegularExpressionValidator to validate the length of the textbox.. however based on your comment see the javascript solution below.
http://forums.asp.net/t/1026502.aspx
pure javascript - something like this should work fine.:
<div id="lengthInfo" style="display:none">Too long!!</div>
<script type="text/javascript">
function strLen(textBox) {
var str = textBox.value;
if (str.length > 2) {
document.getElementById("lengthInfo").style.display = 'inline';
}
else {
document.getElementById("lengthInfo").style.display = 'none';
}
}
</script>
<asp:textbox id="textbox1" CssClass="style5" ClientIDMode="Static" runat="server" MaxLength="10" onkeyup="strLen(this)"></asp:textbox>

Categories

Resources