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>
Related
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>
Hi I have created a jquery script, that makes a textbox as autoCompletebox, and it's working very well.
For this script to work, I want to get the Value HiddenField ClientID in jqvalue and OnSelect trigger button in jqbutton.
<asp:HiddenField ID="vendorIDField" runat="server" />
<asp:TextBox ID="TextBox1" runat="server" CssClass="jq-autocbox absfields" pos="c3 r2" igaddl="nofield" jqvalue = "#<%= vendorIDField.ClientID %>" jqcontainer = ".form-content" jqURL = "GetLists.ashx" jqcommand = "GetVendors" jqbutton = '#<%= Button2.ClientID %>' Width="250px" ></asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button" />
But the ClientID is not compiling. In browser it appears like what I type inside single quotes.
You can assign the value to attribute in code behind using Attributes collection.
TextBox1.Attribute["jqvalue"] = vendorIDField.ClientID;
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.
I'm running into a bit of an issue. I have some asp.net controls wrapped in an update panel, but when I click the submit button it jumps to the top of the page. I've read a bunch of posts on here, and they either require use of some javascript or say set the MaintainPagePostion to "true" in the page directive. I tried setting it to true, that did not work. I really don't want to use a javascript script to accomplish this either. I was under the impression that this is one of the benefits to using an update panel. However, the part that I find most confusing, is it used to not do this. I don't remember changing anything on the website that would have caused this. Any help with this problem is appreciated. Thanks.
Here is the code I'm using.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlEmailStuff" runat="server">
Name: <asp:TextBox ID="txtName" runat="server" Width="202px"></asp:TextBox><br />
Email: <asp:TextBox ID="txtEmail" runat="server" Width="203px"></asp:TextBox><br />
<span style="font-size:12px; font-weight:normal; margin-left:55px;">**Please double check email**</span><br />
Message:<br />
<asp:TextBox ID="txtMessage" runat="server" Width="370px" TextMode="MultiLine" Font-Names="Tahoma" Font-Size="Small" Height="75px"></asp:TextBox><br />
<asp:Label ID="lblEmailError" runat="server" Text="" Font-Size="Small" ForeColor="Red"></asp:Label>
<asp:ImageButton Height="25px" Width="60px" CssClass="EmailSubmit" ImageUrl="Images/MailingListBtnSubmit2.png" ID="btnSubmit" runat="server" onclick="btnSubmit_Click"/>
</asp:Panel>
<asp:Panel ID="pnlThankYou" runat="server" Visible="false">
<p style="text-align:center; font-size:30px;">Thank you!<br /><span style="font-size:20px;">Your Email has been sucessfully submitted.</span></p>
</asp:Panel>
</ContentTemplate>
You can do it in 4 ways :
From Code-behind - Page.MaintainScrollPositionOnPostBack = true;
From Page Directive - MaintainScrollPositionOnPostback="true"
From Web.config - <pages maintainScrollPositionOnPostBack="true" />
Using Javascript. You can use the code from following link. It worked for me -
http://weblogs.asp.net/andrewfrederick/archive/2008/03/04/maintain-scroll-position-after-asynchronous-postback.aspx
I think, it's not jump to the top of the page. It's refreshing the page. What's your update panel's UpdateMode? Is it Conditional? If it's conditional, check trigger. ControlID should be button ID and EventName='Click'. Then check the area of Update Panel .
Sample Code Here :
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlEmailStuff" runat="server">
Name: <asp:TextBox ID="txtName" runat="server" Width="202px"></asp:TextBox><br />
Email: <asp:TextBox ID="txtEmail" runat="server" Width="203px"></asp:TextBox><br />
<span style="font-size:12px; font-weight:normal; margin-left:55px;">**Please double check email**</span><br />
Message:<br />
<asp:TextBox ID="txtMessage" runat="server" Width="370px" TextMode="MultiLine" Font-Names="Tahoma" Font-Size="Small" Height="75px"></asp:TextBox><br />
<asp:Label ID="lblEmailError" runat="server" Text="" Font-Size="Small" ForeColor="Red"></asp:Label>
<asp:ImageButton Height="25px" Width="60px" CssClass="EmailSubmit" ImageUrl="Images/MailingListBtnSubmit2.png" ID="btnSubmit" runat="server" onclick="btnSubmit_Click"/>
</asp:Panel>
<asp:Panel ID="pnlThankYou" runat="server" Visible="false">
<p style="text-align:center; font-size:30px;">Thank you!<br /><span style="font-size:20px;">Your Email has been sucessfully submitted.</span></p>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Have you specified the triggers in the update panel? If you specify the triggers in the triggers section then the update panel will update without jumping on top.Also you need to give updatemode = "conditional". It can be done like this:
<asp:UpdatePanel ID="ex" runat="server" UpdateMode="Conditional">
<ContentTemplate>
//your controls here
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="yourbuttonid" />
</Triggers>
</asp:UpdatePanel>
Well thank you to everyone that gave me suggestions. As it turns out the Page Routing is what caused this issue. So all I had to do to get it working was add and ignore line for that page in my RegisterRoutes code block:
void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("Mobile");
routes.Ignore("Booking.aspx*");//<---- This Fixed it.
routes.MapPageRoute("Gallery", "Gallery/{Name}", "~/Gallery.aspx");
routes.Ignore("*");//<---- This is better for me. It acts as a catch all.
}
This helped me solve the issue: http://forums.asp.net/t/1743640.aspx
EDIT
I added the "routes.Ignore("");" code to it to act as a catch all, so I really don't need to ignore "Booking.aspx" specifically. Keep in mind though the order is important here. The Ignore("") needs to be the last one or else none of the other routing will work.
Thanks again Everyone.
Please try PageRequestManager handlers
<script>
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
try {
sender._controlIDToFocus = null;
}
catch (e) {
}
}
</script>
I was stuck for a few hours with a similar problem. I was convinced the problem was the UpdatePanel but it ended up being the defaultfocus & defaultbutton attributes in the form tag that was causing the page to jump up to focus the first textbox at the top of the page.
<form id="form1" runat="server" defaultbutton="buttonId" defaultfocus="textboxId">
This is something else to look at when facing this kind of issue.
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