JQuery to enable,disable textbox is not working consistently - c#

I have a DropDownList as a custom control inserted into a subform which is within a popup window on my main page. I have coded unique CssClass identifiers for both the DropDownList and the textbox I am trying to enable/disable. I only want the textbox enabled for DropDownList values 317 and 318, all others should disable the textbox. Here is the problem... If I bring up my popup window and select an action other than 317/318, it disables the textbox as expected. Then if I change my mind and select 317 or 318 it DOES NOT enable the textbox. This seems real strange that it partially works.
I have the following jquery code in my main page:
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION)
$(".statusActionAmountCssClass").attr('enabled', 'enabled');
else
$(".statusActionAmountCssClass").attr('disabled', 'disabled');
});
}
</script>
Here is the custom control with the DropDownList:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="StStatusActionLookup.ascx.cs" Inherits="Company.Solutions.Web.Controls.StStatusActionLookup" %>
<div id="mainControlContainer" style="width:99%; padding:8px;">
<div id="comboContainer" style="float:left; padding-top:12px;padding-left:5px; padding-right:5px; padding-bottom:3px;">
<asp:UpdatePanel ID="update1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkComments" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="chkDenials" EventName="CheckedChanged" />
<asp:AsyncPostBackTrigger ControlID="chkOther" EventName="CheckedChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddlLookup" width="240px" CssClass="statusActionDDLCssClass" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="filterContainer" style="text-align:left;padding-left:6px;width:275px">
<fieldset style="width:260;">
<legend>Filters</legend>
<asp:CheckBox ID="chkComments" runat="server" Text="Comments" AutoPostBack="true" />
<asp:CheckBox ID="chkDenials" runat="server" Text="Denials" AutoPostBack="true" />
<asp:CheckBox ID="chkOther" runat="server" Text="Other" AutoPostBack="true" />
</fieldset>
</div>
</div>
And here is my subform with the text box (txtStatusActionAmount):
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="StatusActionAddSubform.ascx.cs"
Inherits="Company.Solutions.Web.Controls.StatusActionAddSubform" %>
<%# Register TagPrefix="st" TagName="StatusActionLookup" Src="~/Controls/StStatusActionLookup.ascx" %>
<div class="NinetyNinePercentWide">
<div class="NinetyNinePercentWide EightPixelBottomMargin">
<div class="RowHeader" style="padding-top: 20px;">
<span>Action:</span>
</div>
<div>
<xy:StatusActionLookup ID="statusActionLookup1" runat="server" />
</div>
</div>
<div class="NinetyNinePercentWide EightPixelBottomMargin">
<div class="quarterWidthDiv">
<span>New Status:</span>
<asp:Literal runat="server" Text=" " ID="spc2" />
<asp:DropDownList runat="server" ID="ddlNewStatus">
<asp:ListItem Selected="True" Value="" Text="" />
<asp:ListItem Value="01" Text="Open" />
<asp:ListItem Value="02" Text="Closed" />
</asp:DropDownList>
</div>
<div class="quarterWidthDiv">
<span>Date:</span>
<asp:Literal runat="server" Text=" &nbsp" ID="spc1" />
<asp:TextBox ID="txtStatusActionDate" runat="server" Columns="10" MaxLength="10"
Style="width: 35%;" CssClass="statusActionDate" />
<cc1:CalendarExtender ID="txtStatusActionDate_CalendarExtender" runat="server" Enabled="True"
TargetControlID="txtStatusActionDate" />
<cc1:MaskedEditExtender runat="server" ID="txtStatusActionDate_MaskedEditExtender"
Enabled="True" Mask="99/99/9999" MaskType="Date" TargetControlID="txtStatusActionDate"
UserDateFormat="MonthDayYear" />
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtStatusActionDate"
Type="Date" Operator="DataTypeCheck" ErrorMessage="Invalid Date" > </asp:CompareValidator>
</div>
<div class="quarterWidthDiv">
<asp:Label runat="server" ID="lblStatusActionAmount" AssociatedControlID="txtStatusActionAmount"
Text="Amount:" />
<asp:TextBox ID="txtStatusActionAmount" runat="server" Style="width: 30%;" CssClass="statusActionAmountCssClass" />
</div>
<div class="quarterWidthDiv">
<asp:Label runat="server" ID="lblClaimant" AssociatedControlID="ddlClaimant" Text="Claimant:" />
<asp:DropDownList ID="ddlClaimant" runat="server" onchange="mailOrStatusActionTextChanged()">
<asp:ListItem Selected="True" Value="" Text="" />
<asp:ListItem Value="1" Text="Primary" />
<asp:ListItem Value="2" Text="Secondary" />
</asp:DropDownList>
</div>
</div>
<div class="NinetyNinePercentWide EightPixelBottomMargin" style="margin-top: 2px;">
<div class="RowHeader">
<asp:Label runat="server" ID="lblStatusActionReason" AssociatedControlID="txtStatusActionReason"
Text="Reason:" />
</div>
<div style="padding-left: 12px;">
<asp:TextBox ID="txtStatusActionReason" runat="server" TextMode="MultiLine" Rows="2"
MaxLength="25" CssClass="StatusReasonWidth" onchange="mailOrStatusActionTextChanged()" />
<asp:CustomValidator ID="cstmValStatusActionReason" runat="server" ControlToValidate="txtStatusActionReason"
ErrorMessage="String is too long" />
</div>
</div>
</div>
Thank you,
Jim in Suwanee, GA

I don't believe there is a 'enabled' property of form elements, try
$(".statusActionAmountCssClass").attr('disabled', false);
EDIT
Note that the meaning and usage of attr() has changed in jQuery 1.6. While the above will probably still work, make sure to test and understand the difference between attr() and prop()
http://blog.jquery.com/2011/05/03/jquery-16-released/
In the 1.6 release we’ve split apart the handling of DOM attributes
and DOM properties into separate methods. The new .prop() method sets
or gets properties on DOM elements, and .removeProp() removes
properties. In the past, jQuery has not drawn a clear line between
properties and attributes. Generally, DOM attributes represent the
state of DOM information as retrieved from the document, such as the
value attribute in the markup . DOM
properties represent the dynamic state of the document; for example if
the user clicks in the input element above and types def the
.prop("value") is abcdef but the .attr("value") remains abc.

$(".statusActionAmountCssClass").attr('disabled', true) won't work
use :$(".statusActionAmountCssClass").attr('disabled', 'disabled')
and $(".statusActionAmountCssClass").removeAttr('disabled', 'disabled')
this will work

This is how i do it.
$("input[name='votingmode']").change(function () {
if ($("input[name='votingmode']:checked").val() == '1') {
$("#plusplus").attr("disabled", "disabled");
$("#minusminus").attr("disabled", "disabled");
} else if ($("input[name='votingmode']:checked").val() == '3') {
$("#plusplus").removeAttr("disabled", "disabled");
$("#minusminus").removeAttr("disabled", "disabled");
});

Related

Page scrolls back on each post back

i have successfully completed my web application for an organization and it works up to expectations but i noticed one problem and tried to cure it via searching on Google and asking seniors but none of these helped much.
Problem: I have multiple drop downs lists on page, in which selecting value in one drop down triggers the loading of another drop down i.e. Country > cities situation, problem is that whenever i click any value it scrolls page to the top and i have to scroll back again then again and again which realy looks bad and unprofessional. Please help me.
Code:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="frmReceivedSms.aspx.cs" Inherits="SmsComplaints" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%# Register assembly="Microsoft.ReportViewer.WebForms,Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
$(document).ready(function () {
$("#btnSendSms").hide();
$("#btnDelete").hide();
$("#btnCancel").hide();
$("#lblSelectedID-Span").hide();
$("#txtSelectedID-Span").hide();
var showHide = $("#HiddenFieldShowHideButtons").val();
if (showHide == "True") {
$("#btnSendSms").show();
$("#btnDelete").show();
$("#btnCancel").show();
$("#lblSelectedID-Span").show();
$("#txtSelectedID-Span").show();
$("#buttonSearch").hide();
$("#Save-Span").hide();
$("#HiddenFieldShowHideButtons").val("False");
}
$("#btnSendSms").click(function () {
$("#ConfirmMsg").text("Are you sure to update this record?");
$("#Delete-Span").hide();
$("#lblSelectedID-Span").hide();
$("#txtSelectedID-Span").hide();
$("#Save-Span").show();
$("#buttonSearch").show();
$("#Update-Span").show();
$("#btnSendSms").hide();
$("#btnDelete").hide();
$("#btnCancel").hide();
$("#ModalConfirmAction").modal({ show: true })
});
$("#btnDelete").click(function () {
$("#ConfirmMsg").text("Are you sure to delete this record?");
$("#Update-Span").hide();
$("#lblSelectedID-Span").hide();
$("#txtSelectedID-Span").hide();
$("#Delete-Span").show();
$("#Save-Span").show();
$("#buttonSearch").show();
$("#btnDelete").hide();
$("#btnSendSms").hide();
$("#btnCancel").hide();
$("#ModalConfirmAction").modal({ show: true })
});
$("#btnCancel").click(function () {
$("#btnSendSms").hide();
$("#btnDelete").hide();
$("#btnCancel").hide();
$("#lblSelectedID-Span").hide();
$("#txtSelectedID-Span").hide();
$("#buttonSearch").show();
$("#Save-Span").show();
ClearTextBoxes();
});
});
function ClearTextBoxes() {
$("input[type=text]").each(function () {
$(this).val("");
});
}
function validate() {
var setValue = false;
var NotificationSummary = new Array();
var fields = new Array("Admin Role");
var txtboxes = new Array($("#txtAdminName"));
$(txtboxes).each(function (index) {
if ($(this).val() == "") {
NotificationSummary[index] = fields[index];
setValue = true;
}
});
if (setValue == true) {
$("#ConfirmMsg").text = NotificationSummary.join(",");
$("#ModalConfirmAction").modal({ show: true })
}
return setValue;
}
$("#Save-Span").click(function () {
validate();
});
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<%--<script type="text/javascript"> //Maintain scroll on post back but doesn't load values in relevant drop down
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get('ContentPlaceHolder1').scrollLeft;
yPos = $get('ContentPlaceHolder1').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('ContentPlaceHolder1').scrollLeft = xPos;
$get('ContentPlaceHolder1').scrollTop = yPos;
}
</script>--%>
<div class="widget">
<div class="widget-header">
<div class="title">
Received Complaints Via Sms
</div>
<!-- widget title-->
</div> <!-- widget header -->
<div class="widget-body">
<div class="row-fluid">
<!-- cons start -->
<div class="shortcut-group">
<asp:HiddenField ID="HiddenFieldSetMessage" runat="server"
ClientIDMode="Static"/>
<asp:HiddenField ID="HiddenFieldShowMessage" runat="server"
ClientIDMode="Static"/>
<asp:HiddenField ID="HiddenFieldIsValidDropDownValue" runat="server"
ClientIDMode="Static" />
<asp:UpdatePanel ID="updGridViewSMS" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<label><b>Search By Date Range</b></label>
<asp:Label ID="lblDateFrom" runat="server" Text="From"></asp:Label>
<asp:TextBox ID="txtFromDate" runat="server" ></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderFromDate" Format="dd/MMM/yyyy" TargetControlID="txtFromDate" runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server"
ControlToValidate="txtFromDate" Display="None" ErrorMessage=""
ForeColor="Red" >
</asp:RequiredFieldValidator>
<asp:Label ID="lblDateTo" runat="server" Text="To"></asp:Label>
<asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderToDate" Format="dd/MMM/yyyy" TargetControlID="txtToDate" runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server"
ControlToValidate="txtToDate" Display="None" ErrorMessage=""
ForeColor="Red" >
</asp:RequiredFieldValidator>
<asp:Button ID="btnSearchByDate" CssClass="btn btn-success" runat="server" Text="Search"
ClientIDMode="Static" OnClick="btnSearchByDate_Click" />
<asp:ValidationSummary
HeaderText="Requires Date Range:"
DisplayMode="SingleParagraph"
EnableClientScript="true"
ForeColor="Red"
runat="server" ID="ValidationSummary1"/>
<label runat="server" id="lblSelectionMessage" style="color:navy; font-size:12px; font-style:italic" visible="false">
Please select one validity dropdown at a time
</label>
<asp:GridView ID="GridViewSmsComplaints" AllowPaging="True" PageSize="5" runat="server" AutoGenerateColumns="False" CssClass="mGrid" BorderColor="#333333" Width="650px" OnRowDataBound="GridViewSmsComplaints_RowDataBound" OnPageIndexChanging="GridViewSmsComplaints_PageIndexChanging" >
<Columns>
<asp:BoundField HeaderText="Sms ID" DataField="ID" />
<asp:BoundField HeaderText="Recieving Date" DataField="RecievingDate" />
<%--<asp:BoundField HeaderText="ToMobileNo" DataField="ToMobileNo" /> --%>
<asp:BoundField HeaderText="Complainant Mob No." DataField="FromMobileNo" />
<asp:BoundField HeaderText="Complaint" DataField="Message" >
<ItemStyle Wrap="True" />
</asp:BoundField>
<asp:TemplateField HeaderText="Complete/InComplete">
<ItemTemplate>
<%--<asp:CheckBox ID="ckboxIsComplaint" runat="server" />--%>
<asp:DropDownList ID="ddlIsComplaint" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlIsComplaint_SelectedIndexChanged">
<asp:ListItem Text="-Select-" Value="-1"></asp:ListItem>
<asp:ListItem Text="InComplete" Value="0"></asp:ListItem>
<asp:ListItem Text="Complete" Value="1"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Panel ID="pnlBoxesDropDowns" runat="server">
<label>Complainant</label>
<asp:TextBox ID="txtComplainant" runat="server" CssClass="textField_width"></asp:TextBox>
<asp:RequiredFieldValidator ID="ReqFieldValdiatorComplainant" runat="server" ControlToValidate="txtComplainant" ErrorMessage="Complainant is Required" ForeColor="Red" SetFocusOnError="True" ValidationGroup="Complaints">Complainant is Required
</asp:RequiredFieldValidator>
<label style="width:400px">Relevant Region</label>
<asp:DropDownList ID="ddlRegions" runat="server" CssClass="DropDown_Width" Width="147px" OnSelectedIndexChanged="ddlRegions_SelectedIndexChanged" AppendDataBoundItems="True" AutoPostBack="true" >
<asp:ListItem Value="-1" Selected="True">-Select-</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="ReqFieldValidatorRegions" runat="server"
ControlToValidate="ddlRegions" ErrorMessage="Region is Required" InitialValue="-1"
ForeColor="Red" ValidationGroup="Complaints">Region is Required</asp:RequiredFieldValidator>
<label style="width:400px">Relevant District</label>
<asp:DropDownList ID="ddlDistricts" runat="server" CssClass="DropDown_Width" Width="147px" OnSelectedIndexChanged="ddlDistricts_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="ReqFieldValidatorDistricts" runat="server"
ControlToValidate="ddlDistricts" ErrorMessage="Region is Required" InitialValue="-1"
ForeColor="Red" ValidationGroup="Complaints">District is Required</asp:RequiredFieldValidator>
<label>Relevant P.Station</label>
<asp:DropDownList ID="ddlPoliceStations" runat="server" Width="147px" CssClass="DropDown_Width">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="ReqFieldValidatorPoliceStations" runat="server"
ControlToValidate="ddlPoliceStations" ErrorMessage="Police Station is Required" InitialValue="-1"
ForeColor="Red" ValidationGroup="Complaints">Police Station is Required</asp:RequiredFieldValidator>
<label>Priority</label>
<asp:DropDownList ID="ddlPriority" runat="server">
<asp:ListItem Text="Top" Value="1"></asp:ListItem>
<asp:ListItem Text="Normal" Value="2"></asp:ListItem>
</asp:DropDownList>
</asp:Panel>
<br />
<br />
<asp:Timer runat="server" Interval="60000" ID="RefreshSmsComplaints" OnTick="RefreshSmsComplaints_Tick" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RefreshSmsComplaints" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnSendSms" ValidationGroup="Complaints" runat="server" CssClass="btn btn-success"
OnClick="btnSendSms_Click" Text="Send Sms" />
<%--<asp:Button ID="btnGenerateReport" CssClass="btn btn-success" runat="server" Text="Generate Report"
ClientIDMode="Static" OnClick="btnGenerateReport_Click" />--%>
<br />
<br />
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="550px">
<LocalReport ReportPath="Reports\GetReceivedComplaintsReport.rdlc">
</LocalReport>
</rsweb:ReportViewer>
<br />
<br />
&nbsp
</div> <!-- shourtcut group">
<!-- cons end -->
</div> <!-- row fluid -->
</div> <!-- widget body-->
</div> <!-- widget-->
<div class="clearfix"></div>
<!-- Modal -->
</asp:Content>
even i used maintainscrollbackposition attribute in page directive and code but it doesn't work, i am using firefox. Even i used this code after scriptmanager tag but it works not perfectly like it maintain scroll back position of page but doesn't load values in drop down upon clicking.
<script type="text/javascript">
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get('scrollDiv').scrollLeft;
yPos = $get('scrollDiv').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('scrollDiv').scrollLeft = xPos;
$get('scrollDiv').scrollTop = yPos;
}
</script>
As an alternative, you can use Focus() method on your first Dropdownlist selection,
Consider this is an example
On Code Behind
Protected void ddlstate_click(object sender, Eventargs e)
{
ddlcity.Focus();
}
It will do the trick as you want.

Asp.NET: How to keep focus on textbox in a nested Update Panel

I am working on making a semi simple post and reply/forum pages in asp.net(with C#). Everything works however when I went to add update panels it makes me want to throw my head into a wall.
I use a DataList to display the posts. I use a form consisting of two textboxes and a button to insert a new post. One textbox if for the name, and the other for the message.
First update panel I added (nested) is to provide a character count for the post. I have a label in the Content and it is triggered by the textboxes textchanged event. The textbox 'txtMessage' also has a java-script function run 'onkeyup' to keep the focus on the textbox when typing. I limit the characters at 1000.
The next update is to surround the DataList so that it does not post back everytime (if not used and the back button is hit it will go back and visually remove each post which is not a good design practice). However when I just put the panel around the DataList it did not postback the insert form so the boxes were not cleared. Which I would like to be done, so I wrapped everything then by this updatepanel, which then made the character count update panel nested by this one. This now works, but the focus is taken off of the txtMessage box each time the textchanged event fires. So the JavaScript is not firing now?
I have moved the opening and closing of the update panel countless times and have tried different fixes, so any further suggestions would help. The code is below.
ForumT.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForumT.aspx.cs" Inherits="UPE_Site_v1.ForumT" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="headPlaceHolder" runat="server">
<script type="text/javascript">
function reFocus(id) {
__doPostBack(id, '');
document.getElementById(id).blur();
document.getElementById(id).focus();
}
</script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetPosts" TypeName="TimeTrackerRepository" DataObjectTypeName="System.Guid" DeleteMethod="DeletePost"> </asp:ObjectDataSource>
<asp:UpdatePanel ID="upDataList" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div>
<asp:DataList ID="DataList2" runat="server" CellPadding="4" DataSourceID="ObjectDataSource1"
ForeColor="#333333" OnItemCommand="DataList2_ItemCommand" OnItemDataBound="DataList2_ItemDataBound"
DataKeyField="PostID" OnItemCreated="DataList2_ItemCreated">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#D4EBD4" />
<ItemTemplate>
<div class="row">
<div class="col-xs-12 col-sm-6">
Name: <strong><%# Eval("Name") %></strong>
</div>
<div class="col-xs-12 col-sm-6">
<%# Eval("TimePosted") %>
</div>
<div class="col-xs-12" style="word-break: break-all">
<%# Eval("Message") %>
</div>
</div>
<br />
<asp:Button ID="btnDelete" CssClass="btn btn-warning" runat="server" Text="Delete" CommandArgument='<%# Eval("PostID") %>' CommandName="DeleteItem" />
<asp:LinkButton CssClass="btn btn-primary" ID="lkbtnFullPost" runat="server" Text="See Full Post" CommandArgument='<%# Eval("PostID") %>' CommandName="FullPost"></asp:LinkButton>
</ItemTemplate>
<SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:DataList>
</div>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<br />
<br />
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">
<p>Add a post to this forum:</p>
<div class="form-group">
<asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label>
<asp:TextBox CssClass="form-control" ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtName"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
</div>
<%--<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>--%>
<div class="form-group">
<asp:Label ID="Label2" runat="server" Text="Message: "> </asp:Label>
<asp:TextBox onkeyup="reFocus(this.id);" CssClass="form-control" ID="txtMessage" runat="server" TextMode="MultiLine" Rows="4" OnTextChanged="txtMessage_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="This is a required field." ValidationGroup="Application"
Display="Dynamic" ForeColor="Red">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtMessage"
ErrorMessage="Character limit is 1000 characters."
ValidationGroup="Application" Display="Dynamic" ForeColor="Red"
ValidationExpression=".{0,1000}">
</asp:RegularExpressionValidator>
</div>
<br />
<%--</div>
</div>--%>
<%--</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>--%>
<%--<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 col-sm-offset-1 col-md-offset-2 col-lg-offset-3">--%>
<asp:UpdatePanel ID="upMessage" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCharacterCount" runat="server">0/1000</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMessage" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ValidationGroup="Application" CssClass="btn btn-default" ID="btnPost" runat="server" Text="POST IT" OnClick="btnPost_Click" />
<asp:Label ID="lblError" runat="server" Text="" CssClas="Error" ForeColor="Red"></asp:Label>
</div>
</div>
<br />
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
ForumT.aspx.cs
only including the textchanged event
protected void txtMessage_TextChanged(object sender, EventArgs e)
{
lblCharacterCount.Text = txtMessage.Text.Count().ToString() + "/1000";
if (txtMessage.Text.Count() >= 1000)
{
lblCharacterCount.ForeColor = System.Drawing.Color.Red;
}
else
{
lblCharacterCount.ForeColor = System.Drawing.Color.Black;
}
}
Sorry for the code being a little sloppy. Also side not, I am using bootstrap so that is what all of the div's are for
I was facing the same issue as I needed to set focus on the textbox after postbacks in update panel. So I researched over internet & found this Javascript code. I tried it & it is working perfectly. It adds event listener for update panel for before & after postback. Gets textbox id before postback & set it after completion of postback.
var lastFocusedControlId = "";
function focusHandler(e) {
document.activeElement = e.originalTarget;
}
function appInit() {
if (typeof (window.addEventListener) !== "undefined") {
window.addEventListener("focus", focusHandler, true);
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}
function pageLoadingHandler(sender, args) {
lastFocusedControlId = typeof (document.activeElement) === "undefined"
? "" : document.activeElement.id;
}
function focusControl(targetControl) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var focusTarget = targetControl;
if (focusTarget && (typeof (focusTarget.contentEditable) !== "undefined")) {
oldContentEditableSetting = focusTarget.contentEditable;
focusTarget.contentEditable = false;
}
else {
focusTarget = null;
}
targetControl.focus();
if (focusTarget) {
focusTarget.contentEditable = oldContentEditableSetting;
}
}
else {
targetControl.focus();
}
}
function pageLoadedHandler(sender, args) {
if (typeof (lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") {
var newFocused = $get(lastFocusedControlId);
if (newFocused) {
focusControl(newFocused);
}
}
}
Sys.Application.add_init(appInit);
Just use this code in your script on aspx page.
You say your javascript is not working. When using update panels and js you will need to rebind your js subscribed events.
Reference: jQuery $(document).ready and UpdatePanels?

show div dynamically when user entered number in a textbox

I have textbox with an id #txtUserEntry where user can put the number of their family member living in their house and a button #btnAddOccupant to click after they put a number in textbox and #divOccupantProfile should show up depends on the number entered so it means 1 family member is equal to 1 #divOccupantProfile
aspx code
<tr>
<td style="text-align:left"><asp:Label ID="lbUserEntry" runat="server" Text="Number of House occupant"></asp:Label></td>
<td><asp:TextBox ID="txtUserEntry" class="basetxt" runat="server" Width="290"></asp:TextBox></td>
</tr>
<tr>
<td style="text-align:left"><asp:Button ID="btnAddOccupant" runat="server" Text="+" />
<asp:Label ID="lbres5" runat="server" Text="Add Occupant"></asp:Label></td>
</tr>
divOccupantProfile
<div id="divOccupantProfile">
<asp:Label ID="OPfamilyname" runat="server" Text="Family Name"></asp:Label>
<asp:TextBox ID="textOPfamilyname" runat="server"></asp:TextBox><br />
<asp:Label ID="OPfirstname" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="textOPfirstname" runat="server"></asp:TextBox><br />
<asp:Label ID="OPmiddlename" runat="server" Text="Middle Name"></asp:Label>
<asp:TextBox ID="textOPmiddlename" runat="server"></asp:TextBox><br />
<asp:Label ID="OPmaritalstatus" runat="server" Text="Marital Status"></asp:Label>
<asp:DropDownList ID="ddlOPmaritalstatus" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Married</asp:ListItem>
<asp:ListItem>Single</asp:ListItem>
<asp:ListItem>Divorced</asp:ListItem>
</asp:DropDownList><br />
<asp:Label ID="OPoccupation" runat="server" Text="Occupation"></asp:Label>
<asp:TextBox ID="textOPoccupation" runat="server"></asp:TextBox><br />
<asp:Label ID="OPrelationship" runat="server" Text="Relationship"></asp:Label>
<asp:DropDownList ID="ddlOPrelationship" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Wife</asp:ListItem>
<asp:ListItem>Daughter</asp:ListItem>
<asp:ListItem>Son</asp:ListItem>
<asp:ListItem>Father</asp:ListItem>
<asp:ListItem>Mother</asp:ListItem>
<asp:ListItem>House helper</asp:ListItem>
<asp:ListItem>Driver</asp:ListItem>
</asp:DropDownList>
</div>
can someone show me an example how to do this one
something like
$('#btnAddOccupant').click(function(){
var occupants = $('#txtUserEntry').val();
//here some check on occupants.....
for(int i = 0;i<occupants;i++){
$(somewhere).append($('#divOccupantProfile').html());
}
})
Some suggestions:
because you are going to use multiple divOccupantProfile, it's better to use selectors based on the class instead of ID, otherwise in your page you'll have 1+ elements with the same ID.
The $(somewhere)
is the "container" where you want to put all the div related to each occupant profile
Also note that the .html() function will copy the html INSIDE the div, exluding the div itself. So if you want to have N elements formed in this way
<div class="occupantProfile">...</div>
<div class="occupantProfile">...</div>
you have to use
somewhere.append($('<div').append($('.occupantProfile')).html())
Here i have made a sample for what you should find helpful
HTML
<input type="text"http://jsfiddle.net/#save id="txtnum" />
<input type="button" value="click" id="btnSubmit" />
<div id="divOccupantProfile1">Data 1</div>
<div id="divOccupantProfile2">Data 2</div>
<div id="divOccupantProfile3">Data 3</div>
<div id="divOccupantProfile4">Data 4</div>
<div id="divOccupantProfile5">Data 5</div>
CSS
div[id^="divOccupantProfile"] {
display:none;
}
Jquery
$("#btnSubmit").click(function(){
var num = $("#txtnum").val();
$("#divOccupantProfile"+ num).css("display","block");
})
Demo Link

Asp .Net UpdatePanel not working

I am using an UpdatePanel to show some controls that are normally hidden.
This is the code that I am using:
<asp:LinkButton runat="server" class="btn blue h27" CausesValidation="false" ID="lnkSuggestArticle"
OnClick="lnkSuggestArticle_Click"><%=Supplier.GetResource("Answers_lnkSuggestArticle")%> <i class="icon icon_next_02 fr"></i></asp:LinkButton>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div class="infoRequest" id="divSuggestion" runat="server" visible="false">
<br class="clearfix" />
<h3>
Please provide the information you want to see on our support site:</h3>
<br class="clearfix" />
<asp:TextBox runat="server" ID="txtSuggestArticle" Rows="10" ValidationGroup="s" Width="100%"
TextMode="MultiLine"></asp:TextBox>
<div id="divEmailAddress" runat="server" visible="false">
<br />
<h3>
Please enter your email address</h3>
<asp:TextBox runat="server" ID="txtEmailAddress" Rows="1" ValidationGroup="s" CssClass="suggestionEmail"
TextMode="SingleLine"></asp:TextBox>
<br />
</div>
<br />
<asp:Label runat="server" ID="lblSugestedArticleError" ForeColor="Red" Visible="false"></asp:Label>
<asp:Label runat="server" ID="lblMessage" ForeColor="Red"></asp:Label>
<br />
<asp:LinkButton ID="btnSaveSuggestion" ValidationGroup="s" runat="server" OnClick="btnSaveSuggestion_Click"
CssClass="btn blue fr"><%=Supplier.GetResource("createticket_btnSuggest")%> <i class="icon icon_next_02 fr"></i></asp:LinkButton>
<%--<input type="submit" value="Suggest" class="btnSuggest" />--%>
<br />
<br />
<p id="notice" runat="server">
<asp:Label runat="server" ID="lblSuggestionNote" /></p>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkSuggestArticle" />
</Triggers>
</asp:UpdatePanel>
When the user clicks the lnkSuggestArticle button I execute the following code:
protected void lnkSuggestArticle_Click(object sender, EventArgs e)
{
divSuggestion.Visible = true;
if ((WFSS.DataAccess.Entities.Customer)Session["__currentCustomer"] == null)
{
divEmailAddress.Visible = true;
}
}
But it doesn't update the page. The div still stays hidden when the user clicks the suggest button.
protected void lnkSuggestArticle_Click(object sender, EventArgs e)
{
divSuggestion.Visible = true;
if (Session["__currentCustomer"] == null)
{
divEmailAddress.Visible = true;
}
}
It turns out that there was a bug in Visual Studio. I had commented a piece of code in the aspx file. Turns out even though it appeared to be commented the code still executed which caused another update panel to be added which gave me an error in javascript.

UpdatePanel triggers UpdateProgress of other usercontrol also in asp.net webform

I am working on a webform which has two UpdatePanels; one inside UserControl and other inside the main page. When the pager user-control (< 1 2 3 >) of Main page is invoked it shows the corresponding UpdateProgress of 'Latest News' Section but also shows the Progress Bar of 'Subscribe' User-control.
I tried to change the properties but it keeps on coming; if I keep UpdateMode="Conditional" for user control then progress bar goes in loop and show continuously.
How can I make changes to this code to show only corresponding progress bar. I have looked over 50 example but nun seems to be matching. I would appreciate if someone can help me to get this fixed.
<!-- LatestNewArea -->
<div class="LatestNewArea">
<asp:UpdatePanel ID="updLatestNews" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Repeater ID="rptLatestNews" runat="server" EnableViewState="False" onitemdatabound="rptLatestNews_ItemDataBound">
<ItemTemplate>
<asp:HyperLink ID="hylLatestNews" CssClass="chylLatestNews" runat="server" NavigateUrl=''>
<div class="LatestNewsWrapper">
<div class="LatestNewsDateBox">
<div class="LNYYYY">
<asp:Label ID="lblYYYY" runat="server" Text="2012"></asp:Label>
</div>
<div class="LNDDMM">
<asp:Label ID="lblDDMM" runat="server" Text="12/08"></asp:Label>
</div>
</div>
<div class="LatestNewsTitle">
<asp:Label ID="lblLatestNewsTitle" runat="server" Text="First News for the Website"></asp:Label>
</div>
<div class="LatestNewsHDate">
<asp:Label ID="Label1" runat="server" Text="Hijri: 15 Rajab 1433"></asp:Label>
</div>
<div class="LatestNewsDesc">
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</div>
</div>
<div class="LNHLine"> </div>
</asp:HyperLink>
</ItemTemplate>
</asp:Repeater>
<!-- Pager -->
<div class="LatestNewsPagerWrapper">
<div class="LatestNewsPagerInnerWrapper">
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="50" AssociatedUpdatePanelID="updLatestNews" >
<ProgressTemplate>
<div id="imgLoadingArticleList" class="imgLoadingArticleList">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/images/ajax-loader-bar2.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<uc1:PagerControl ID="PagerControl1" runat="server" CssClass="gold-pager" PageMode="LinkButton" />
</div>
</div>
<!-- Pager -->
</ContentTemplate>
</asp:UpdatePanel>
</div>
<!-- LatestNewArea -->
User Control Page Code
<script type="text/javascript">
function onUpdating() {
// get the divImage
var panelProg = $get('divImage');
// set it to visible
panelProg.style.display = '';
// hide label if visible
var lbl = $get('<%= this.pnlSubscribe.ClientID %>');
lbl.innerHTML = '';
}
function onUpdated() {
// get the divImage
var panelProg = $get('divImage');
// set it to invisible
panelProg.style.display = 'none';
}
</script>
<table cellpadding="0" cellspacing="0" class="SubscribeContainer">
<tr>
<td align="center">
<table cellpadding="0" cellspacing="0" class="SubscribeWrapper" border="0">
<tr>
<td valign="top">
<asp:UpdatePanel ID="updSubscribe" runat="server" >
<ContentTemplate>
<asp:Panel ID="pnlSubscribe" runat="server" Height="10px">
<div class="SubHeading"><asp:Label ID="lblTitle" runat="server" Text="JOIN US"></asp:Label></div>
<div class="dSubName">
<asp:TextBox ID="txtName" CssClass="txtSubscribe" runat="server" Text="NAME" onfocus="if(this.value=='NAME')this.value='';" onblur="if(this.value=='')this.value='NAME';"></asp:TextBox>
</div>
<div class="dSubEmail">
<asp:TextBox ID="txtEmail" CssClass="txtSubscribe" runat="server" Text="YOUR EMAIL" onfocus="if(this.value=='YOUR EMAIL')this.value='';" onblur="if(this.value=='')this.value='YOUR EMAIL';"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmailSub" runat="server" ErrorMessage="*"
ControlToValidate="txtEmail" ValidationGroup="SubEmail" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmailSub" runat="server"
ErrorMessage="*" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="SubEmail" ></asp:RegularExpressionValidator>
</div>
<div class="dSubSubmit">
<asp:Button ID="btnSubscribe" CssClass="btnSubscribe" runat="server" ValidationGroup="SubEmail" Text="Subscribe" onclick="btnSubscribe_Click" />
</div>
</asp:Panel>
<div class="dSubMSG">
<asp:Label ID="lblMSG" runat="server" Text=""></asp:Label>
</div>
<div id="divImage" style="display:none" class="dSubAni">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/loader-sub.png" Visible="true"/>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1" TargetControlID="updSubscribe" runat="server">
<Animations>
<OnUpdating>
<Parallel duration="0">
<ScriptAction Script="onUpdating();" />
<EnableAction AnimationTarget="btnSubscribe" Enabled="false" />
</Parallel>
</OnUpdating>
<OnUpdated>
<Parallel duration="0">
<ScriptAction Script="onUpdated();" />
<EnableAction AnimationTarget="btnSubscribe" Enabled="true" />
</Parallel>
</OnUpdated>
</Animations>
</asp:UpdatePanelAnimationExtender>
</td>
</tr>
</table>
</td>
</tr>
</table>
I tried many solution but non of them worked in a proper way. Finally i decided to replace UpdatePanelAnimationExtender of user control with UpdateProgress as I was able to trap the initiating UpdatePanel for AsyPostback
For some reason i was not able to trap AsyPostback when i used UpdatePanelAnimationExtender
BELOW IS A WORKING CODE
// Function to hide control on update
function onUpdateOfSubscribe() {
var panelProg = $get('divImage');
// set it to visible
panelProg.style.display = '';
// hide label if visible
var lbl = $get('<%= this.pnlSubscribe.ClientID %>');
lbl.innerHTML = '';
}
//Code to track the initiating event so to associate updateprogress
var currentPostBackElement;
function pageLoad() {
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_initializeRequest(OnInitializeRequest);
}
//On OnInitializeRequest
function OnInitializeRequest(sender, args) {
var manager = Sys.WebForms.PageRequestManager.getInstance();
currentPostBackElement = args.get_postBackElement().parentElement;
var cmdAuthoriseButton = '<%= btnSubscribe.ClientID %>';
if (cmdAuthoriseButton == args._postBackElement.id) {
// Show UpdateProgress for subscribe
onUpdateOfSubscribe();
}
}
</script>
<table cellpadding="0" cellspacing="0" class="SubscribeContainer">
<tr>
<td align="center">
<table cellpadding="0" cellspacing="0" class="SubscribeWrapper" border="0" >
<tr>
<td valign="top">
<asp:UpdatePanel ID="updSubscribe" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Panel ID="pnlSubscribe" runat="server" Height="10px">
<div class="SubHeading"><asp:Label ID="lblTitle" runat="server" Text="JOIN US"></asp:Label></div>
<div class="dSubName">
<asp:TextBox ID="txtName" CssClass="txtSubscribe" runat="server" Text="NAME" onfocus="if(this.value=='NAME')this.value='';" onblur="if(this.value=='')this.value='NAME';"></asp:TextBox>
</div>
<div class="dSubEmail">
<asp:TextBox ID="txtEmail" CssClass="txtSubscribe" runat="server" Text="YOUR EMAIL" onfocus="if(this.value=='YOUR EMAIL')this.value='';" onblur="if(this.value=='')this.value='YOUR EMAIL';"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmailSub" runat="server" ErrorMessage="*"
ControlToValidate="txtEmail" ValidationGroup="SubEmail" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmailSub" runat="server"
ErrorMessage="*" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="SubEmail" ></asp:RegularExpressionValidator>
</div>
<div class="dSubSubmit">
<asp:Button ID="btnSubscribe" CssClass="btnSubscribe" runat="server" ValidationGroup="SubEmail" Text="Subscribe" onclick="btnSubscribe_Click" />
</div>
</asp:Panel>
<div class="dSubMSG">
<asp:Label ID="lblMSG" runat="server" Text=""></asp:Label>
</div>
<div id="divImage" style="display:none" class="dSubAni">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/loader-sub.png" Visible="true"/>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubscribe" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updSubscribe" >
<ProgressTemplate>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>
</table>
</td>
</tr>
</table>

Categories