Can't get the RadSearchBox text by javascript - 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

Related

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

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>

Required Field Validation in javascript

I tried this code for validating empty field,But it doesn't works properly when call javascript it does not focus on Textbox,and code will execute continues.
Html Code:
<asp:TextBox ID="txtholdername" runat="server" Width="60%"></asp:TextBox>
<asp:TextBox ID="txtusername" runat="server" Width="60%"></asp:TextBox>
<asp:ImageButton ID="btnsave" runat="server" OnClientClick="javascript:return validateRegistrationMaster();" ImageUrl="~/Images/save.png" />
Script
function IsBlank(obj) {
if (obj) {
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; }
if ((obj.value.trim().length == 0) || (obj.value == null)) {
obj.focus();
return false;
}
return true;
}
}
function validateRegistrationMaster() {
var Holder_Name = document.getElementById('<%= txtholdername.ClientID %>');
var username = document.getElementById('<%= txtusername.ClientID %>');
if ((!IsBlank(Holder_Name))) {
Holder_Name.focus();
return false;
}
if ((!IsBlank(username))) {
username.focus();
return false;
} return true;
}
Use Required Field Validator instead of custom Javascript, while using Asp.Net Controls.
Example : Click Here W3 Schools Link
Code:
<asp:RequiredFieldValidator ControlToValidate="txtholdername" Text="The holder name field is required!"
runat="server" />
<asp:RequiredFieldValidator ControlToValidate="txtusername" Text="The user namefield is required!"
runat="server" />

Get element by id in javascript without having any form tag on page

I am wondering if it is possible to get the element by id in javascript when there is no form tag available.
I am using the following command to get the text box value but i am getting error message 'null or undefined'. This works fine if i use proper form tag on asp.net page.
var _txt = document.getElementById("txt").value;
Is there any other way of getting textbox values in javascript (when there is no form,body and header tag in asp.net page)
Here is the code
enter code here
<asp:dropdownlist runat="server" ID="ddl" Height="20px"
Width="215px" ValidationGroup="aa">
<asp:ListItem Selected="True" Value="0">--select--</asp:ListItem>
<asp:ListItem Value="1">item-1</asp:ListItem>
</asp:dropdownlist>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="ddl" ErrorMessage="required" InitialValue="0"
SetFocusOnError="True" Display="Dynamic" ValidationGroup="aa"></asp:RequiredFieldValidator>
<br />
<asp:textbox runat="server" ID="txt" ValidationGroup="aa" Width="140px"></asp:textbox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txt" ErrorMessage="required" InitialValue=""
SetFocusOnError="True" Display="Dynamic" ValidationGroup="aa"></asp:RequiredFieldValidator>
<br />
</div>
<div>
<asp:validationsummary runat="server" ID="valSummary"
HeaderText="Vendor Ref and Contact are required" ValidationGroup="aa"
CssClass="valsummary">
</asp:validationsummary>
</div>
<asp:Button ID="btn" runat="server" Text="DO" ValidationGroup="aa"
Width="118px" OnClientClick="Test2()"/>
<br />
<script type="text/javascript" language="javascript">
function Test() {
var _indx = document.getElementById('ddl');
var _txt = document.getElementById("txt").value;
if (_indx.selectedIndex == 0 || _txt == '') {
document.getElementById('_div').style.visibility = 'visible';
document.getElementById('_div').style.display = "block";
}
else {
document.getElementById('_div').style.visibility = 'hidden';
document.getElementById('_div').style.display = "none";
}
}
function Test2() {
var _indx = document.getElementById('ddl');
var _txt = document.getElementById("txt").value;
var msg_I = "........"
var msg_II = "...."
var msg_III = ".."
if (_indx.selectedIndex == 0 && _txt == '') {
txtHeader = msg_I
}
else if (_indx.selectedIndex == 0 && _txt != '') {
txtHeader = msg_III
}
else if (_indx.selectedIndex != 0 && _txt == '') {
txtHeader = msg_II
}
document.getElementById('<%= valSummary.ClientID %>').headertext = txtHeader;
} </script>
Change var _txt = document.getElementById("txt").value; to:
var _txt = document.getElementById("<%= txt.ClientID %>").value;
ClientID returns you generated ID to use in your client code.

Categories