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

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>

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

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

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.

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 %>');

How to get the Textbox's ID inside a Gridview using JQuery?

I have searched for a while but i couldn't find an answer to my situation
This is my problem:
I have a Textbox inside a Gridview like this:
<asp:TemplateField HeaderText="<%$ Resources:DCAAStrategicManagement, obj_lblStandardWeight %>" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtStandardWeight" onkeypress="return onlyNumbers();" Text='<%# Eval("StandardWeight") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
And i need to set a blur event on that TextBox using JQuery.
This is my attempt to achieve that:
$("input[id*='<%=txtStandardWeight.ClientID %>']").blur(function () {
Read();
var currentSum = document.getElementById('<%=hidden.ClientID %>').value;
var oldLabelData = $('#<%= lblStandardWeightCurrently.ClientID %>').value;
var newLabelData = oldLabelData + currentSum;
$('#<%= lblStandardWeightCurrently.ClientID %>').value(newLabelData);
})
This function should change the lblStandardWeightCurrently Text whenever the blur even occurs.
But There is no changes in lblStandardWeightCurrently label..
Read() Function:
function Read() {
debugger;
var oDataGrid = document.getElementById("<%= grdPlanObjectivesStandardWeights.ClientID %>");
var tableRows = oDataGrid.rows;
var sum = 0;
for (var i = 1; i < tableRows.length; i++) {
var col1 = oDataGrid.rows[i].cells[2];
for (j = 0; j < col1.childNodes.length; j++) {
if (col1.childNodes[j].type == "text") {
if (!isNaN(col1.childNodes[j].value) && col1.childNodes[j].value != "") {
sum += parseInt(col1.childNodes[j].value)
}
}
}
}
if (!isNaN(sum)) {
document.getElementById('<%=hidden.ClientID %>').value = sum;
}
}
I think the problem is here:
$("input[id*='<%=txtStandardWeight.ClientID %>']").blur(function ()
since i can't debug this function .
Any help would be appreciated.
Note that your textbox is inside a template. That means that it actually does not exist until grid view is databound, and even what it is, there are many textboxes, one per row, each having a different ID. That means that you cannot simply access it by txtStandardWeight.
However since you are using jQuery anyway, why don't assign some class to the textbox which would allow you to query for it easily?
<asp:TextBox runat="server" ID="txtStandardWeight" CssClass="weightText" ...
$("input.weightText").blur(function () {
One more thing - make sure your javascript is defined in .aspx file, otherwise syntax <%# %> won't work.
$().ready(function () {
$("#<%= text.ClientID%>").find("tr").each(function () {
$(this).find("td").each(function () {
$(this).find("input[id*=txtStandardWeight]").blur(function () {
alert("Hello");
});
});
});
});
Let's take an example where gridview has id=text and your textbox has an id=txtStandardWeight then we have to traverse each row and column to get proper result and when you find your textbox then manage the proper functioning according to you.

How to get the gridview textbox control ID in javascript?

I have ASP.NET Gridview and Textbox control in it. Now I want to get the Textbox ID in java script.
I had already referred this question in stack overflow but I couldn't get the exact answer.
My Gridview Template Code is
<asp:TemplateField HeaderText="Amt Recieve Now" ControlStyle-Width="100">
<ItemTemplate>
<asp:TextBox ID="txtAmountReceiveNow" runat="server" CssClass="textboxRight"
AutoPostBack="true" OnFocus= "GVtxtAmount()"
OnTextChanged="txtAmountReceiveNow_TextChange"
Text='<%#Eval("AMOUNT_RECEIVE_NOW")%>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and Javascript code is as follows :
function GVtxtAmount() {
var txtAmountReceive = document.getElementById(
'<%= ((GVMaintainReceiptMaster)Container)
.FindControl("txtAmountReceiveNow").ClientID %>');
var selection = txtAmountReceive.value.indexOf(".");
alert(selection);
};
GVMaintainReceiptMaster is ID of GridView
Help me to overcome this problem.
Try this
function GVtxtAmount() {
var txtAmountReceive = $("input[id*=txtAmountReceiveNow]")
var selection = txtAmountReceive.value.indexOf(".");
alert(selection);
};
You can't get text box in this way. Here is the work-around I hope it will help.
function GVtxtAmount() {
var GVMaintainReceiptMaster = document.getElementById('<%= GVMaintainReceiptMaster.ClientID %>');
for (var rowId = 1; rowId < GVMaintainReceiptMaster.rows.length; rowId++) {
var txtbx = GVMaintainReceiptMaster.rows[rowId].cells[0].children[0];
alert(txtbx.value);
}
return false;
}

Categories