send ASP.Net Control Id To a JavaScript Function - c#

I have 2 views. The last control on view1 is txtName & the first control on view2 is txtAge. Need to change the focus from txtName to txtAge on TAB press, but I fail to acheive this.
ASPX:
<asp:Multiview ID ="multiview1" runat="server" ActiveViewIndex="0">
<asp:view ID="view1" runat="server">
<asp:Textbox id="txtName" runat="server"
onfocusout="SetFocus('<%=txtAge.ClientId%>');"></asp:TextBox>
</asp:view>
<asp:view ID ="view2" runat="server">
<asp:Textbox id="txtAge" runat="server" ></asp:TextBox>
</asp:view>
</asp:Multiview>
JS:
function SetFocus(controlId){
/*alert(controlId);*/
document.getElementById(controlId).focus();
}
When I check the alert, it shows <%=txtAge.ClientId%> in the popup. Where is this going wrong.
Here is my new finding:
This code works well when the target control is in the same view, but when it is in another view, then it doesnt. So I think, something else should also be done to change the view first and then worry about the focus:
<asp:Textbox id="txtName" runat="server"
onfocusout="SetFocus();"></asp:TextBox>
function SetFocus(){
document.getElementById('<%=txtEmail.ClientID%>').focus();
/* txtEmail is in the same view 'view1' as in txtName */
}

You can try setting it in server-side code:
txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');", txtAge.ClientId);

Perhaps it is sufficient to use tabindex
http://msdn.microsoft.com/en-us/library/ms178231%28v=vs.100%29.aspx
that uses build in features rather then javascript.
if you use asp.net 4.x you can use clientidmode=static
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
<asp:Multiview ID ="multiview1" runat="server" ActiveViewIndex="0">
<asp:view ID="view1" runat="server">
<!-- other controls -->
<asp:Textbox id="txtName" runat="server" TabIndex="1"/>
</asp:view>
<asp:view ID ="view2" runat="server">
<asp:Textbox id="txtAge" runat="server" TabIndex="2"/>
<!-- other controls -->
</asp:view>
</asp:Multiview>
edit
if you do not mind using jQuery. You can wrap a div around <asp:View.. and then do something like:
$("div.view input:last-child").on("change", function(){
$(this).parent().next().find("input:first-child").focus();
});
please keep in mind that this is pseudo code. It is just an idea.

Try this and see if it's any better.
<asp:Textbox id="txtName" runat="server"
onfocusout='<%= String.Format("SetFocus(\"{0}\");", txtAge.ClientId) %>'></asp:TextBox>

It is not possible to set an attribute using an inline block in that situation... as you can see you are getting the literal <%=txtAge.ClientId%> text, and you are not getting the processed value that you are expecting.
You have two obvious solutions...
The first one (which Yuriy has already given you in his answer) is to set it from the code behind...
txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');",
txtAge.ClientId);
(Disclaimer, I don't know what the MultiView is, as I've never used it, so I'm not 100% sure the 2nd option below will actually work in your scenario. Also, it is untested code.)
The other is to use what Murali provides in his answer, but with additional manipulation...
<asp:Textbox id="txtName" runat="server" onfocusout="SetFocus(this);" />
function SetFocus(nameCtrl) {
var ageId = nameCtrl.id.replace(/txtName/,"txtAge");
var ageCtrl = document.getElementById(ageId);
ageCtrl.focus();
}

Change line onfocusout="SetFocus('<%=txtAge.ClientId%>');"></asp:TextBox>
as onfocusout="SetFocus('txtAge');"></asp:TextBox>
You don't need to send ClientId

Related

Calling a function on a HTML check box change without submission using C#

I am using Visual Studio 2015 to create a ASP.NET web site. I have a DIV that is hidden by default and I am trying to display it if the user checks a check box. I am wondering if there is a way using C# to immediately display the DIV as soon as the user checks the box. I can't seem to find a way to recognize the change in state without the form being first submitted. I can easily achieve this using JavaScript however this is for a uni assignment and requires functionality to be implemented in C#.
This is the HTML for the checkBox:
<form id="form1" runat="server">
Limit Stations To My Location<asp:CheckBox ID="limitOptions" runat="server" onClick="toggleOptions()" />
<br /><br />
<div id="locationOptions" runat="server" hidden="hidden">
Radius (KM)<asp:TextBox ID="radius" runat="server" Text="100"></asp:TextBox>
<asp:Button ID="updateList" runat="server" Text="Button" OnClick="updateList_Click"/>
</div>
Any help would be greatly appreciated.
You can do this with C# in code behind. Add a OnCheckedChanged event to the CheckBox and set the AutoPostBack to true and handle the change. Note that a Panel becomes a div in HTML.
<asp:CheckBox ID="limitOptions" runat="server" OnCheckedChanged="limitOptions_CheckedChanged" AutoPostBack="true" />
<asp:Panel ID="locationOptions" runat="server" Visible="false">
Radius (KM) <asp:TextBox ID="radius" runat="server" Text="100"></asp:TextBox>
</asp:Panel>
However this causes a PostBack, so just using JavaScript could be a better option.
<asp:CheckBox ID="limitOptions" runat="server" onclick="toggleOptions()" />
<div id="locationOptions" runat="server" style="display: none">
Radius (KM)<asp:TextBox ID="radius" runat="server" Text="100"></asp:TextBox>
</div>
<script type="text/javascript">
function toggleOptions() {
var id = '#<% =locationOptions.ClientID %>';
if ($(id).css('display') == 'none') {
$(id).slideDown('fast', function () { });
} else {
$(id).slideUp('fast', function () { });
}
}
</script>

<%= %> tag not working to display content inside an ASP Label control

Noob question.
Why does this not work into my .aspx file?
<body>
<asp:Label ID="Label1" runat="server" Text='<%=System.DateTime.Today.Day.ToString()%>' ></asp:Label>
</body>
It does display the <%=System.DateTime.Today.Day.ToString()%> string which is obviously not what I want.
Same result if I try to display the content of a code behind variable:
<asp:Label ID="label" runat="server" Text='<%= versionNumber %>' >
versionNumber being properly instanced and set into the code behind.
You cannot mix server controls with code blocks.
There are two ways to work around that limitation:
Just use <%=System.DateTime.Today.Day.ToString()%> without a Label around it
Use codebehind to set Label1.Text = System.DateTime.Today.Day.ToString();
The first way will display the date to the user, but you cannot further change it from codebehind.
The second way does enable you to alter the text from codebehind.
It is true you can't mix server controls with Code blocks,
If its compulsory for you to use Server side control, and you don't even want to set value from code behind then you can go for this solution.
<asp:Label ID="Label1" runat="server"><%=System.DateTime.Today.Day.ToString() %></asp:Label>
Similarly you can use code behind variable as follows ,
<asp:Label ID="Label1" runat="server"><%=versionNumber %></asp:Label>
If you really want to use a asp:Label
Use it as follows:
<asp:Label ID="Label1" runat="server"><%=System.DateTime.Today.Day.ToString() %></asp:Label>

RadAjaxLoadingPanel does not works with DNN

I have a dnn site, which has a label and an imagebutton, clicking on which replaces the label with textbox and user can enter their text, once submitted the label will be updated with this text. Now clicking on the imagebutton causes the page to postback, i don't want a postback for this, hence i have placed telerik RadAjaxLoadingPanel control, so the cool loading div gets displayed while processing is going on, but for some reason it's not working, It always throws below error:
Please, see whether wrapping the code block, generating the exception, within RadCodeBlock resolves the error.
Below is the markup of my page: (I tried the wrapping the code with RadScriptBlock and RadCodeBlock, in both case it throws same error as above)
<telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<a class="subscribetoday" href="#">
<strong>Subscribe Today!</strong> <asp:Label ID="lblsubscribemsg" runat="server" Text="12 issues for $14.95"></asp:Label>
<asp:ImageButton ID="imgEditSubscribe" runat="server"
OnClick="imgEditSubscribe_Click" ToolTip='Edit' ImageUrl="~/images/edit.gif" AlternateText='Edit' Visible="false" />
<div id="editsubscribe" runat="server" visible="false">
<asp:TextBox ID="txtSubscribe" runat="server"></asp:TextBox> <asp:ImageButton ID="imgSave" runat="server"
OnClick="imgSave_Click" OnClientClick="return validateSubscribeNote();" ToolTip='Save' ImageUrl="~/images/save.gif" AlternateText='Save' /> <asp:ImageButton ID="imgCancel" runat="server"
OnClick="imgCancel_Click" ToolTip='Cancel' ImageUrl="~/images/cancel.gif" AlternateText='Cancel' />
</div>
<img src="img/prosound-subscribe.png" alt="Subscribe Today!">
</a>
</telerik:RadScriptBlock>
</telerik:RadAjaxPanel>
Can anyone tell me where i am going wrong with this.
The problem is with other server code blocks on the page (<%=%> for example, generally - <% ... %>), not with this concrete piece of code you are trying to AJAX-enable. You can read more here: http://docs.telerik.com/devtools/aspnet-ajax/controls/ajax/radcodeblock-and-radscriptblock
So, you should find the place where those code blocks are used and wrap THEM in a RadCodeBlock controls. It is often scripts that reference controls, e.g.:
<telerik:RadCodeBlock runat="server" ID="RadCodeBlock1">
<script>
function getReference() {
return $find("<%=someControl.ClientID%>");
}
</script>
</telerik:RadCodeBlock>
With DNN, however, I cannot say where these may originate.
Thus, your other option is to use an <asp:UpdatePanel> control to get AJAX requests instead of full postbacks. The native AJAX toolset also offers the <asp:UpdateProgress> control that you can use instead of RadAjaxPanel.

enable and disable asp validator using embedded code in asp tag dosent work

enable and disable asp validator using embedded code in asp tag doesn't work, The value is written but control still is enabled. Please check the occurrences of
Enabled="<%# Convert.ToBoolean(txtText.Enabled) ? false : true%>"
in this form:
<form id="frmValidator" runat="server">
<div>
<asp:ValidationSummary
ID="Summary"
runat="server"
HeaderText="Error(s):"
CssClass="msg-error" />
<asp:TextBox ID="txtText" runat="server" MaxLength="15" Enabled="false" />
<asp:RequiredFieldValidator
ID="rfvtxtText"
runat="server"
ControlToValidate="txtText"
ErrorMessage="Requiered."
Display="None"
ClientValidationFunction=""
SetFocusOnError="true"
Enabled="<%# Convert.ToBoolean(txtText.Enabled) ? false : true%>" />
<asp:RegularExpressionValidator
ID="revtxtText"
runat="server"
ControlToValidate="txtText"
Display="None"
ErrorMessage="Invalid."
ValidationExpression="[a-zA-ZñÑáéíóúÁÉÍÓÚ ,.*]{3,50}"
SetFocusOnError="true"
Enabled="<%# Convert.ToBoolean(txtText.Enabled) ? false : true%>" />
<asp:Button
ID="btnSave"
runat="server"
Text="Save" />
</div>
<form>
The answer is you cannot.
<%# %> is Data Binding Expression Syntax. You cannot use it without ServerControl such as GridView, ListView.
Normally, we disable/enable control from code behind.
Javascript Method
Another approach is to disable validation using Javascript. However, you need to redirect to different page or do something after a button click. Otherwise, validation message will be displayed back to user after post back.
<script type="text/javascript">
if (document.getElementById('<%= txtText.ClientID %>').getAttribute('disabled') === 'disabled') {
alert('disabled');
ValidatorEnable(document.getElementById('<%= rfvtxtText.ClientID %>'), false);
ValidatorEnable(document.getElementById('<%= revtxtText.ClientID %>'), false);
}
</script>
In my opinion, it should be possible. Though I'm still a rookie myself, I always forget which code-nugget does what. I'd try <%: --expression-- %>.The second answer to this question does a pretty good summary.

update textbox when changed without refreshing

I'm working on my own aspx program and now i have a calculator which i want to be able to fill in some values and when you press tab to the next value and fill it in it will automatically calculate and write it into a textbox(or label). this must be without having to refresh the page.
would this be possible in combination with c# or would i need to look for php + ajax to get this done?
i had the following coded:
<asp:TextBox ID="tbx_rms" onchanged="textboxcalc" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_volt" onchanged="textboxcalc" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw1" Enabled="false" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw2" Enabled="false" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_eff" onchanged="textboxcalc" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw3" Enabled="false" runat="server"></asp:TextBox>
and this is the c# code:
public void textboxcalc(object sender, EventArgs e)
{
if (tbx_rms.Text != "" && tbx_volt.Text != "")
{
double rms = Convert.ToDouble(tbx_rms.Text);
double volt = Convert.ToDouble(tbx_volt.Text);
double ant = Convert.ToDouble(rms / volt);
if (tbx_eff.Text != "")
{
double effi = Convert.ToDouble(tbx_eff.Text);
double tot = Convert.ToDouble((effi / ant) * 100);
tbx_anw3.Text = Convert.ToString(tot);
}
tbx_anw1.Text = Convert.ToString(ant);
tbx_anw2.Text = Convert.ToString(ant);
}
I hope it is clear enough what my intentions are and if not i will happily answer any questions.
after listening to the comments i just went ahead and used javascript to make this calculation.
<script type="text/javascript">
function calctxtboxes() {
var rms = document.getElementById('<%=tbx_rms.ClientID%>').value;
var volt = document.getElementById('<%=tbx_volt.ClientID%>').value;
var effi = document.getElementById('<%=tbx_eff.ClientID%>').value;
if (rms != "" && volt !="") {
var ant = rms / volt;
document.getElementById('tbx_anw1').value = ant;
document.getElementById('tbx_anw2').value = ant;
if (effi != "") {
var total = (ant / effi)*100;
document.getElementById('tbx_anw3').value = total;
}
}
}
</script>
and the aspx like this:
<asp:TextBox ID="tbx_rms" onchange="calctxtboxes()" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_volt" onchange="calctxtboxes()" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw1" Enabled="false" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw2" Enabled="false" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_eff" onchange="calctxtboxes()" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw3" Enabled="false" runat="server"></asp:TextBox>
You can achieve this by using UpdatePanel with control triggers and setting AutoPostback="true" for the textboxes that caused the event.
<asp:TextBox ID="tbx_rms" onchanged="textboxcalc" AutoPostback="true" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_volt" onchanged="textboxcalc" AutoPostback="true" runat="server"></asp:TextBox>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbx_rms" />
<asp:AsyncPostBackTrigger ControlID="tbx_volt" />
<asp:AsyncPostBackTrigger ControlID="tbx_eff" />
</Triggers>
<ContentTemplate>
<asp:TextBox ID="tbx_anw1" Enabled="false" runat="server"></asp:TextBox>
<asp:TextBox ID="tbx_anw2" Enabled="false" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="tbx_eff" onchanged="textboxcalc" AutoPostback="true" runat="server"></asp:TextBox>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tbx_rms" />
<asp:AsyncPostBackTrigger ControlID="tbx_volt" />
<asp:AsyncPostBackTrigger ControlID="tbx_eff" />
</Triggers>
<ContentTemplate>
<asp:TextBox ID="tbx_anw3" Enabled="false" runat="server"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
You could use an UpdatePanel control. The refresh would be done using ajax behind the scenes, so the page wouldn't flash.
However, for something simple like this, c# might be overkill. You could solve this particular problem with simple javascript.
use ajax in asp.net by using update panel you can achieve this functionality.
I've used this plugin in my previous projects
http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
As you can see by the examples it's pretty straight forward, you may want to lookup jQuery selectors as well. For simple calculations like yours, as stated above using server side to calculate it maybe overkill.
Firstly, PHP is not required, C# is not really required either unless you want to do something when the value gets back to the server, JavaScript is the best option for you, of the 3 that have been mentioned. If you are doing Mathematics be aware that JavaScript does not always behave the same way as C# does with regard to rounding and possibly other types of mathematics, but I have experienced rounding quirks between both languages.
If you can cause you textbox to be updated via some client script (probably a form of JavaScript) then all you would be required to do as a user is click the submit button and the value will be sent back to the server as it already does, assuming you want the value sent back to the server.
Simply implement the calculation you have already in C# in a client script so the textbox is updated, then postback the value by clicking on the submit button, capture the value and do what you want with it. Note, the textbox you are putting the calculation in already exists in the code so your value will be sent back to server when you click the existing submit button, again, assuming you want the value to be posted back to the server.
If you are unsure how to do this then implement what you know how to do and comment back here about what you have done by updating your question with the new code you have created, specify where you are stuck and we can direct you further with the problem.
You will want to use a library for doing the JavaScript, but here is an example I have just written for you to play with, you probably won't want to use it for your stuff as I am sure is is pretty awful in its implementation, but it should help you see a little of what it should be like in terms of amount of code required and simplicity, should also show you that the C# approach is a bit too much for what you are wanting to do.
<html>
<head>
<title>Calculations</title>
<script type="text/javascript">
function UpdateCalculation(f)
{
if (f.tbx_rms.value !== "" && f.tbx_volt.value !== "")
{
var rms = f.tbx_rms.value;
var volt = f.tbx_volt.value;
var ant = rms / volt;
if (f.tbx_eff.value !== "")
{
var effi = f.tbx_eff.value;
var tot = (effi / ant) * 100;
f.tbx_anw3.value = tot;
}
f.tbx_anw1.value = ant;
f.tbx_anw2.value = ant;
}
}
</script>
</head>
<body>
<form name="calcForm">
<input type="input" id="tbx_rms" name="tbx_rms" onchange="javascript:UpdateCalculation(calcForm)" />
<input type="input" id="tbx_volt" name="tbx_volt" onchange="javascript:UpdateCalculation(calcForm)" />
<input type="input" id="tbx_anw1" name="tbx_anw1" />
<input type="input" id="tbx_anw2" name="tbx_anw2" />
<input type="input" id="tbx_eff" name="tbx_eff" onchange="javascript:UpdateCalculation(calcForm)" />
<input type="input" id="tbx_anw3" name="tbx_anw3" />
</form>
</body>
</html>

Categories

Resources