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.
Related
There is a 4 column grid, in the second column there is a dropdown list whose client change event is wired to trigger some actions based on the value selected. Basically, the control in the 3rd column will be manipulated based off the ddl value and whether a checkbox in the last column is checked.
RadGrid
<telerik:RadGrid ID="theGrid" runat="server">
<MasterTableView ClientDataKeyNames="ProductId" EditMode="InPlace">
<Columns>
<telerik:GridBoundColumn DataField="ProductName" HeaderStyle-Width="120px" HeaderText="Product Name" UniqueName="ProductName" ReadOnly="true"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="ProductServices" HeaderText="QX Services">
<ItemTemplate>
<telerik:RadDropDownList ID="ddlProductServices" runat="server" OnClientItemSelected="productServicesItemSelected"></telerik:RadDropDownList>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="IncludePublicRecordData" HeaderText="Include Public Record Data">
<ItemTemplate>
<asp:CheckBox ID="IncludePublicRecordData" runat="server" Enabled="False" AutoPostBack="false"></asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridCheckBoxColumn DataField="EnablePublicRecordData" UniqueName="hdnEligiblePublicRecordData" ReadOnly="True" HeaderText="Eligible Public Record Data">
</telerik:GridCheckBoxColumn>
</Columns>
</MasterTableView>
<ClientSettings AllowKeyboardNavigation="false" EnableRowHoverStyle="True">
<Selecting AllowRowSelect="false" EnableDragToSelectRows="False" />
</ClientSettings>
</telerik:RadGrid>
Actionable clientside event
I need to know which row is currently in play for this to work. Currently this wonky solution works but ONLY because there is 1 row in the table.
What I'm going to attempt, is spin throw the rows and match the id of the "sender" object to one in one of the cells and use the index of the loop. But that seems so bad and inconsistent (due to the nesting of objects). I'm sure telerik has an easier, cleaner way to accomplish this...thus my plea to the SO community.
function productServicesItemSelected(sender, eventArgs) {
try {
const str = sender._uniqueId;
let parent = sender.get_parent();
const item = eventArgs.get_item();
const selectedValue = item.get_value() || "";
console.log("You selected " + item.get_text() + "; with value " + item.get_value());
let itemParent = item._parent;
let theGrid = $find("<%=ProductServicesGrid.ClientID %>");
if (theGrid) {
let masterTable = theGrid.get_masterTableView();
let rows = masterTable.get_dataItems();
let rowIdx = 0;
if (rows.length > 1) {
console.log("...finding rowIdx:");
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
let cellz = row._element.cells;
if (cellz) {
for (var j = 0; j < cellz.length; j++) {
var celll = cellz[j];
// match item uniqueId with that of each cell
console.log(celll);
}
}
}
}
let currentRow = rows[rowIdx];
let cells = currentRow._element.cells;
//
let eligibleCheckbox = cells[3].firstElementChild.childNodes[0];
let includeCheckbox = cells[2].firstElementChild;
if (selectedValue === "QEWComp" || selectedValue === "none") {
// disable
$(includeCheckbox).attr('disabled', true);
// uncheck
$(includeCheckbox).prop("checked", false);
} else {
if (eligibleCheckbox.checked) {
$(includeCheckbox).attr('disabled', false);
} else {
$(includeCheckbox).attr('disabled', true);
}
}
}
The way that I have done something similar is to pass in the Container.ItemIndex
OnClientItemSelected='<%# string.Format("productServicesItemSelected(this, {0}); return false;", Container.ItemIndex) %>'
The JavaScript function would look like
function productServicesItemSelected(sender, itemIndex) { }
To get the selected row that your dropdown was in you can use:
var theGrid = $find("<%=ProductServicesGrid.ClientID %>");
var masterTableView = theGrid.get_masterTableView();
// clear any previously selected rows
theGrid.clearSelectedItems();
// select the current row by index
masterTableView.selectItem(itemIndex);
var selectedItems = masterTableView.get_selectedItems();
if (selectedItems.length > 0) {}
This will give you the selected row and you can use functions off of selectedItems[0] to get data key values you have defined on the grid like productID
Hopefully this helps somewhat.
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>
I want to insert value from JavaScript variable to the textbox value. In JavaScript variable data is coming very well but when that variable data I am storing in the .net textbox using JavaScript at that time this type of error is coming.
Here is my code
<form>
<asp:TextBox name="password" ID="txt_pass" runat="server"></asp:TextBox>
<asp:Button ID="btn_captcha" runat="server" Text="Gen. Pass." OnClientClick="return false;" ClientIDMode="Static"/>
<script>
$(function () {
$(document).on("click", "#btn_captcha", function (e) {
var length = 5,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
alert(retVal);
document.getElementsByName('password')[0].value = retVal;
});
});
</script>
</form>
You can use Id instead of name
document.getElementById('<%= txt_pass.ClientID %>').value = retVal;
or
document.querySelector('[id$=_txt_pass]').value = retVal;
I think that your problem is that the textbox name and id you are looking for is not static thats why javascript cannot find the element. Press F12 use developer tools to verify the above input's name and id and then use a static one.
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;
}
I am trying for a simple validation which consist of a RadioButtonList rblstPallet. I tried the below code:
javascript
var rblstPallet = document.getElementById('rblstPallet');
var counter = 0;
for (var intCount = 0; intCount < rblstPallet.length; intCount++) {
if (rblstPallet[intCount].checked) { //this step is not working
console.log(intCount); //I checked using this step
counter++;
}
}
if (counter == 0) {
//MSG: please select any item
}
else {
// Redirect to next page function
}
.aspx
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Wood</asp:ListItem>
<asp:ListItem>Plastic</asp:ListItem>
<asp:ListItem>None</asp:ListItem>
</asp:RadioButtonList>
The problem is that if I even select one of the Radio Button, then also the counter value is remaining same. when I debugged the code, I came to know that the line
if (rblstPallet[intCount].checked) {
is not even executing nor even showing any errors in console. I am going through this link. I tried this link(not working).
Please help.
RadioButtoList is converted in radio buttons having id similar to radiobuttonlist id, you need to iterate through DOM to find the matching elements.
function getRadioButtonListSelections(radioButtonListName)
{
int selectionCount = 0;
for(i=0;i<document.forms[0].length;i++)
{
e=document.forms[0].elements[i];
if (e.id.indexOf(radioButtonListName) != -1 && e.checked)
selectionCount++;
}
return selectionCount;
}
alert(getRadioButtonListSelections('rblstPallet'));
Either use:
var rblstPallet = document.getElementById('<%=rblstPallet.ClientID=>');
Or
set the client id mode to static:
<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal" ClientIDMode="static">
And find and loop through each radio button:
var rblstPallet = document.getElementById('rblstPallet');
rblstPallet = rblstPallet.querySelectorAll('input[type="radio"]')
Replace
var rblstPallet = document.getElementById('rblstPallet');
By
var rblstPallet = document.getElementById('<%= rblstPallet.ClientID %>');
If you want to validate your radiobuttonlist why don't you use a validator control ?
<asp:RequiredFieldValidator ID="rfvPallet" runat="server"
ControlToValidate="rblstPallet" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>