Update one textbox using javascript function when another changes - javascript

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

Related

Display the User selected text in Text in Text area

<script type="text/javascript">
/* run on document load **/
function disp() {
//var text = document.getElementById('TextArea1').value;
var text = document.getElementById('MainContent_TextArea1').value;
//alert('a')
if (text == null)
{
return false;
}
else
{
var t = text;
var t = text.substr(text.selectionStart, text.selectionEnd -text.selectionStart);
document.getElementById('displayval').value = t;
alert(t)
}
}
</script>
<div>
<input id="TextArea1" runat="server" type="text"/>
<INPUT type="button" onclick= "disp()" visible="true" value="Show"/>
<INPUT type="text" id ="displayval" visible="true" />
</div>
Here I am trying to display the User selected text through alert. But I want to display this data in Textarea2 through C#. How can I call this function there in C#. Any help please.
Try:
$('#text-area2-id').val(t);
This will show it in text area 2 instead of an alert.
How can I call this function there in C#. ?
You can not. Javascript runs on client side, after server sends everything to the client.
You can call javascript function code behind using
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

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>

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")

Cancel ajax modalpopupextender using javascript

I have a modalpopupextender with a targetcontrolid = buttCopyFormula. The buttCopyFormula is wrapped in a span tag for the user to verify they want to proceed. The button also has a javascript function that verifies there is text in one of the fields and if there is places it in a textbox within the modalpopup.
If there isn't text in the field I want to cancel the popup and display a message.
I've had the span around the button for a while, but am just adding the verification function. I would imagine there is a better way to do this, but just not sure what it is.
What is the best way to execute this functionality?
TargetControl Button
<span onclick="return confirm('Copy the selected formula?')">
<asp:ImageButton ID="buttCopyFormula" ImageAlign="AbsBottom" OnClientClick="transferName()" runat="server" ImageUrl="~/images2020/copy_32.png" />
<b style="color:White">Copy</b>
</span>
Modal Popup
<asp:ModalPopupExtender ID="ModalPopupExtender2" Y="20" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="buttFormulaCancel"
PopupControlID="Panel2" TargetControlID="buttCopyFormula">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel2" runat="server" CssClass="modalQuestionBackground"
Style="display:none"><br />
<h5>Enter a Name for the Formula</h5>
<br /><br />
Formula Name:
<asp:TextBox ID="txtFormulaNameNew" CssClass="controltext" Width="65%" runat="server" Text=""></asp:TextBox><br /><br />
<center>
<asp:Button ID="buttFormulaSaveNew" runat="server" CssClass="button"
OnClick="buttFormulaSaveNew_Click" Text="Save Formula" />
<asp:Button ID="buttFormulaCancel" runat="server" CssClass="button"
Text="Cancel" />
</center>
<br />
</asp:Panel>
JavaScript Function
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (v === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
}
f.value = v
}
I've been working on this and first removed the span around the button, put a fake hyperlink for the modal popup and added a behavior id to the popup. I have also changed the javascript as follows...
New Javascript
function transferName() {
var v = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaNameNew").value;
var f = document.getElementById("ctl00_ContentPlaceHolder1_txtFormulaName");
if (f === "") {
alert("Please select the formula you want to copy before proceeding");
return false;
} else {
if (confirm('Copy selected formula?')) {
f.value = v;
var mod = $find("ModalPopupExtender2");
alert(mod.id.toString);
mod.show;
return false;}
}
}
I still can't get the modalpopup to show. I imagine it's because it's wrapped in an update panel. Any ideas??
You may subscribe to showing event of ModelPopupExtender and cancel showing dependent on some conditions. Put script below at page AFTER THE ScriptManager control
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
function pageLoadedHandler(sender, args){
var popupExtender = $find("ModalPopupExtender2"); // BehaviorId of popup extender
popupExtender.remove_showing(onPopupShowing);
popupExtender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var txtFormulaNameNew;
var txtFormulaName = $get("<%= txtFormulaName.ClientID %>");
if (formulaTextBox.value.length === 0) {
alert("Please select the formula you want to copy before proceeding");
args.set_cancel(true);
} else {
if (confirm('Copy selected formula?')) {
txtFormulaNameNew = $get("<%= txtFormulaNameNew.ClientID %>");
txtFormulaNameNew.value = txtFormulaName.value;
}
}
}

Populate Drop down from Text box in Javascript

I have an asp.net drop down list box and I want to populate it based on the value of the text box via javascript. The value is passed to the stored procedure which I created and the results will be populated in the drop down.
I did my research but I can't seem to find the right solution to this.
Need help please.
[UPDATE]
Here's the source code which I initially did:
HTML:
<asp:DropDownList runat="server" id="cboPriceID" AutoPostBack="true" onblur="LoadPrice()"/>
And I have a dataTable which is retrieved from the stored procedure. What I currently have is a javascript code which populates the textbox.
function LoadPart_CallBack(response) {
//if the server-side code threw an exception
debugger;
if (response.error != null) {
//we should probably do better than this
alert(response.error);
return;
}
var ResponseValue = response.value;
var al = ResponseValue.split(":");
var errormsg = al[0];
var partname = al[1];
if (errormsg == "") {
document.getElementById("<%=txtPartName.ClientID%>").value = partname;
}
}
Need help on how to populate it.
<html>
<body>
<input type="text" id="data" name="data"/>
<input type="button" value="Add" onclick="addData()"><br/>
<select id="choice">
</select>
<script type="text/javascript">
function addData()
{
var txt=document.getElementById("data").value;
if(txt!="")
{
var newcontent = document.createElement('option');
newcontent.innerHTML = txt;
document.getElementById("choice").appendChild(newcontent);
document.getElementById("data").value="";
}
}
</script>
</body>
</html>

Categories

Resources