how to subtract asp textbox values and put result in asp label - javascript

I am trying to get the values from two text boxes, subtract the values and return the difference in an a label as the values are typed in. I have tried the below code and am having no luck. What is the best way to do this? This is running on asp.net page with a master page.
.ASPX
<asp:TextBox ID="txtWeek1FridayAM_IN" runat="server" class="numeric" Width="40px" >0.00</asp:TextBox>
<asp:Label ID="lblWeek1FridayTotalHrs" runat="server" class="numeric" Text="0"></asp:Label>
<asp:TextBox runat="server" ID="txtWeek1FridayAM_OUT" class="numeric" width="40px" OnTextChanged="OUTvalidation" >0.00</asp:TextBox>
aspx.cs
$(document).ready(function () {
sum();
$("#txtWeek1FridayAM_IN, #txtWeek1FridayAM_OUT").on("keydown keyup", function () {
sum();
});
});
function sum() {
var num1 = document.getElementById('#txtWeek1FridayAM_IN').value;
var num2 = document.getElementById('#txtWeek1FridayAM_OUT').value;
var result = parseFloat(num2) - parseFloat(num1);
if (!isNaN(result)) {
document.getElementById('#lblWeek1FridayTotalHrs').value = result;
}
}

Few points:
If you need to reference the control IDs in client-side script, you can use <%= control_id.ClientID %>.
label or span element does not have value property, use textContent instead.
I prefer input instead of keyup and keydown.
I am having some issue with OnTextChanged="OUTvalidation" while running the code. But able to execute successfully by removing that from the control.
Change you code to the following:
$(document).ready(function () {
sum();
$("body").on("input", "#<%=txtWeek1FridayAM_IN.ClientID%>, #<%=txtWeek1FridayAM_OUT.ClientID%>", function () {
sum();
});
});
function sum() {
var num1 = document.getElementById('<%=txtWeek1FridayAM_IN.ClientID%>').value;
var num2 = document.getElementById('<%=txtWeek1FridayAM_OUT.ClientID%>').value;
var result = parseFloat(num2) - parseFloat(num1);
if (!isNaN(result)) {
document.getElementById('<%=lblWeek1FridayTotalHrs.ClientID%>').textContent = result;
}
}

Use this script
$(document).ready(function () {
sum();
$('[id$="txtWeek1FridayAM_IN"], [id$="txtWeek1FridayAM_OUT"]').on("keyup", function () {
sum();
});
});
function sum() {
var num1 = $('[id$="txtWeek1FridayAM_IN"]').val();
var num2 = $('[id$="txtWeek1FridayAM_OUT"]').val();
var result = parseFloat(num2) - parseFloat(num1);
if (!isNaN(result)) {
$('[id$="lblWeek1FridayTotalHrs"]').html(result);
}
}

you can put onkeyup in textbox control
<asp:TextBox runat="server" ID="txtWeek1FridayAM_OUT" class="numeric" width="40px" OnTextChanged="OUTvalidation" onkeyup="sum(); return false" >0.00</asp:TextBox>

Have you tried this with onkeypress="SUM()":
ASP :
<asp:TextBox ID="txtWeek1FridayAM_IN" onkeypress="SUM()" runat="server" class="numeric" Width="40px" >0.00</asp:TextBox>
<asp:Label ID="lblWeek1FridayTotalHrs" runat="server" class="numeric" Text="0"></asp:Label>
<asp:TextBox runat="server" ID="txtWeek1FridayAM_OUT" onkeypress="SUM();" class="numeric" width="40px" OnTextChanged="OUTvalidation" >0.00</asp:TextBox>
Script:
function SUM() {
var num1 = $('input[id=<%=txtWeek1FridayAM_IN.ClientID%>]').val();
var num2 = $('input[id=<%=txtWeek1FridayAM_OUT.ClientID%>]').val();
var result = parseFloat(num2) - parseFloat(num1);
if (!isNaN(result)) {
document.getElementById('<%=lblWeek1FridayTotalHrs.ClientID %>').value = result;
}
}
Please note :
You can specify the javascript method at the time of defining the controls, no need to depend on document.ready for this. like what we did onkeypress="SUM()"
Since you are using ASP controls the ID of the control may not be the same as you defined. master page may also have a role in this. so better to use ClientID

Try this, this will work
.aspx page
<asp:TextBox ID="txtWeek1FridayAM_IN" runat="server" class="numeric" Width="40px" >0.00</asp:TextBox>
<asp:Label ID="lblWeek1FridayTotalHrs" runat="server" class="numeric" Text="0"></asp:Label>
<asp:TextBox runat="server" ID="txtWeek1FridayAM_OUT" class="numeric" width="40px" OnTextChanged="OUTvalidation" >0.00</asp:TextBox>
.cs page
protected void OUTvalidation(object sender, EventArgs e)
{
int val1 = Convert.ToInt32(txtWeek1FridayAM_IN.Text);
int val2 = Convert.ToInt32(txtWeek1FridayAM_OUT.Text);
int val3 = val1 - val2;
lblWeek1FridayTotalHrs.Text = val3.ToString();
}
If you enter values in both the textboxes and click enter on the second textbox it will display value on the label.

Related

Can't get the RadSearchBox text by javascript

<script type="text/javascript">
function getItem() {
var sku = document.getElementById('<%=RadSearchBox1.ClientID%>').value; // Return undefind
document.getElementById('<%= Label1.ClientID %>').innerHTML = sku;
}
</script>
it always return Undefined in Label1
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" OnClientClick="getItem();return false;" />
<asp:Label ID="Label1" runat="server" ></asp:Label>
You can get the input value using the code like this:
<script type="text/javascript">
function getItem() {
var sku = document.getElementById('<%=RadSearchBox1.ClientID%>_Input').value;
document.getElementById('<%= Label1.ClientID %>').innerHTML = sku;
}
</script>
Notice I added _Input in document.getElementById as the search textbox id is different from RadSearchBox control

Accessing a DropDownList from a DetailsView in JavaScript

I have a DetailsView called DetailsView1 as follows with a DropDownList called SupplierDD and a CheckBox called ApprovedCB.
<asp:DetailsView ID="DetailsView1 " runat="server" Width="70%" AutoGenerateRows="False" DataKeyNames="ID" DataSourceID="DetailsViewDS "
DefaultMode="Edit">
<Fields>
<asp:TemplateField HeaderText="Supplier">
<EditItemTemplate>
<asp:DropDownList runat="server" ID="SupplierDD"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approved" SortExpression="ApprovedForOrderFromSupplier">
<EditItemTemplate>
<asp:CheckBox runat="server" ID="ApprovedCB" OnClick="return CheckIfSupplierIsSelected(this);" Checked='<%# Bind("ApprovedForOrderFromSupplier") %> />
..................
I have JavaScript code as following
<script type="text/javascript">
function CheckIfSupplierIsSelected(cb) {
var detailsView = document.getElementById('<%= DetailsView1.ClientID %>');
var supplierDD1 = detailsView.getElementById('<%= SupplierDD.ClientID %>');
//var supplierDD2 = detailsView.child.getElementById('<%= SupplierDD.ClientID %>'); //have tried this way too
if (cb.checked === true) {
alert("checked");
return true;
} else {
alert("unchecked");
return true;
}
}
</script>
The error I am getting is the name SupplierDD does not exist in the current context. Can anyone help me know how to declare the new SupplierDD in the JavaScript. I have tried several ways, as you can see below in the JavaScript to get the SupplierDD. I obviously have no problem with the Checkbox as it is passed with the JavaScript method call in the CheckBox.
Instead of using the following line -
var supplierDD1 = detailsView.getElementById('<%= SupplierDD.ClientID %>');
Try using jQuery find selector like -
var supChk = detailsView.find('<%= SupplierDD.ClientID %>');

javascript add two textbox values and display in third in asp.net

How do I in javascript/asp add two textbox values and display in third?
My JS code
function sum() {
var txtFirstNumberValue = document.getElementById('TextBox1').value;
var txtSecondNumberValue = document.getElementById('TextBox2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('TextBox3').value = result;
}
}
ASP in page load
TextBox1.Attributes.Add("onkeyup", "sum();");
TextBox2.Attributes.Add("onkeyup", "sum();");
One thing you should know:
By default, ASP.NET uses auto-generated ClientID property to be used by TextBox control in ASPX pages, so that your textbox ID will become something like <input id="ctl00_ContentPlaceHolder1_TextBox1" type="text" ... /> after rendered. To use the server control name in client-side you need to use ClientID like this:
function sum() {
var txtFirstNumberValue = document.getElementById('<%= TextBox1.ClientID %>').value;
var txtSecondNumberValue = document.getElementById('<%= TextBox2.ClientID %>').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('<%= TextBox3.ClientID %>').value = result;
}
}
An alternative to avoid using generated ClientID in client-side is setting ClientIDMode to be static, here are examples to use it:
<%-- control level --%>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ... />
<%-- placeholder level --%>
<asp:Content ID="Content1" runat="server" ClientIDMode="Static" ...>...</asp:Content>
<%-- page level --%>
<%# Page Language="C#" ClientIDMode="Static" AutoEventWireup="true" ... %>
Reference:
ClientID Property
Set HTML Attributes for Controls in ASP.NET Web Pages
You can use below code in aspx without using code behind.
<asp:textbox id="TextBox1" cssclass="sum" runat="server" />
<asp:textbox id="TextBox2" cssclass="sum" runat="server" />
<asp:textbox id="txtResult" runat="server" />
<script>
$(document).ready(function () {
//this calculates values automatically
calculateSum();
$(".sum").on("keydown keyup", function () {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".sum").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0) {
$(this).css("background-color", "red");
}
});
$("#<%=this.txtResult.ClientID%>").val(sum.toFixed(2));
}
</script>

getElementByID for templateField TextBox

i have used RowDataBound for gridview. Below is my C# code
protected void gvParameterValue_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
if(condition)
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange();");
}
}
}
Asp.Net code for gridview
<asp:UpdatePanel ID="updatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="gvParameterValue" SkinID="GridView" runat="server" OnRowDataBound ="gvParameterValue_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Location Name">
<asp:TemplateField HeaderText="Parameter Value">
<ItemTemplate>
<asp:TextBox ID="txtValue" SkinID="fineLineTextBox" TabIndex="1" runat="server" AutoPostBack="false"></asp:TextBox>
<%--<asp:TextBox ID="TextBox1" SkinID="fineLineTextBox" TabIndex="1" runat="server" OnTextChanged="textBox1_textChanged" AutoPostBack="true"></asp:TextBox>--%>
<asp:Label ID="lblPreDayVal" runat="server" Text='<%# Bind("PreviousValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate >
</asp:UpdatePanel>
js function as below and i have a problem
function ValueOnChange()
{
var val = document.getElementById('lblPreDayValue').value;
}
It gives error "Microsoft JScript runtime error: Object required"
i have tried all possible solutions from net but nothing works...
You've called getElementById on the ID lblPreDayValue. In your ASP.NET markup you've called it lblPreDayVal.
You might also want to use ClientID to ensure you get the correct ID generated by .NET
You can pass the ClientID from the server-side during the binding step in the gvParameterValue_RowDataBound method like this :-
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
Label lblVal = (Label)e.Row.FindControl("lblPreDayVal");
txtBox.Attributes.Add("onchange", "ValueOnChange('" + lblVal.ClientID + "');");
And then inside the ValueOnChange method definition, pass the argument as cid (lets say).
function ValueOnChange(cid)
{
var val = document.getElementById(cid).innerHTML;
}
Try passing values at the RowBound event of gridview , You are trying to access getElementbyId('lblLocID') is not going to work because it's id will be change when row renders .
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblLocID = (Label)e.Row.FindControl("lblLocationID");
Label lblPreDayValue =(Label)e.Row.FindControl("lblPreDayValue");
if (lblLocID.Text.Equals("154") || lblLocID.Text.Equals("168") || lblLocID.Text.Equals("178"))
{
TextBox txtBox = (TextBox)e.Row.FindControl("txtValue");
txtBox.Attributes.Add("onchange", "ValueOnChange(" + lblPreDayValue.ClientID + ");");
}
}
After passing ClientID to function
//Or you can directly pass the value of label and assign .
function ValueOnChange(ClntID)
{
var val = document.getElementById('ClntID').innerHTML;
}
Try to use
function ValueOnChange()
{
var val = document.getElementById('#<%= lblPreDayVal.ClientID %>').innerHTML;
}
If the above din work then
function ValueOnChange()
{
var val = document.getElementById('lblPreDayVal').innerHTML;
}

textbox value not saving in database

Here is my mark up code:
<p>
<label>Reference Code:</label>
<span class="field">
<asp:TextBox ID="GenerateCode" runat="server" CssClass="smallinput random" ></asp:TextBox>
<asp:HiddenField ID="txthidden" runat="server" />
<br /><small style="color: red">Please write the code at the back of yours check</small>
</span>
</p>
here is my random function:
function randomString()
{
var chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
for (var i = 8; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
here's how i get the random to be displayed in the textbox:
function generateRandomNumber() {
var rndStr = randomString();
$("#<%=GenerateCode.ClientID%>").val(rndStr);
$("#<%=txthidden.ClientID%>").val(rndStr);
}
window.onload = function () {
generateRandomNumber();
}
here's how i save it in the database:
string EchequeMaster = ClassEmailCheque.InsertEmailCheque(SenderID, Convert.ToInt32(ddlCurrency.SelectedIndex), Convert.ToDecimal(Amount.Text), ChequeNumber.Text, GenerateCode.Text, PendingStatus, DateTime.Now);
I solved this by using hidden field...i uodated my codes for reference.
Textboxes that are disabled (property Enabled = false) will not post back any value.
The solution is to have both a disabled textbox (to show the value to the user) and a hidden field which will post back the value. You could re write your code to something like this:
<asp:TextBox ID="txtGenerateCode" runat="server" CssClass="smallinput random" />
<asp:HiddenField ID="hdnGenerateCode" runat="server" class="random" />
function generateRandomNumber() {
var rndStr = randomString();
$(".random").val(rndStr);
}
Hope this helps!

Categories