How to get the gridview textbox control ID in javascript? - 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;
}

Related

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 do I get the selected row in Gridview in Javascript or JQuery

Let me elaborate ... below is my partial gridview with a button field ... what I want is the text value of the button to use in building a url:
<asp:GridView CssClass="gridUser" ID="UsersGrid" ClientIDMode="Static" runat="server" AllowPaging="true" AllowSorting="true" PageSize="5" OnPageIndexChanging="PageIndexChange" OnRowCommand="Paging" OnSorting="SortPage" OnRowCreated="RowCreated"
AutoGenerateColumns="false">
<PagerSettings Mode="NextPreviousFirstLast" FirstPageImageUrl="~/Images/Navigation/firstpageIcon.png" LastPageImageUrl="~/Images/Navigation/lastpageIcon.png"
NextPageImageUrl="~/Images/Navigation/forwardOneIcon.png" PreviousPageImageUrl="~/Images/Navigation/backOneIcon.png" Position="Bottom" />
<Columns>
<asp:TemplateField HeaderText="User Name" HeaderStyle-CssClass="gridHeader">
<ItemTemplate>
<asp:Button ID="UserLink" ClientIDMode="Static" runat="server" Text='<%#Eval("UserName") %>' CssClass="linkButton" OnClientClick = "return GetSelectedRow(this)"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
and here is my javascript :
$(".linkButton").click(function () {
var ul = document.getElementById('UserLink');
var row = ul.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Userid = row.cells[0].childNodes[1].value;
var User = Userid;
alert("Row is : " + row + "RowIndex is : " + rowIndex + "User ID is " + User);
});
My issue is that my row returned is the first row ... not the selected row ... how do I get the selected row? Thank you for any assistance.
Try this... Change naming conventions according to your requirement
<script type = "text/javascript">
function GetSelectedRow(UserLink) {
var row = UserLink.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var Userid = row.cells[0].innerHTML;
alert("RowIndex: " + rowIndex + " Userid : " + Userid + ");
return false;
}
</script>
Your first problem is that in your button template column you are using an Id=UserLink which will get repeated for each row. Your element id's should be unique. See this answer for more details.
Your second problem is that document.getElementById('UserLink'); will actually find the first element with the id of UserLink which is always going to be the first row. In your case you can us var ul = this; and that should give you the button that was actually clicked.
To summarize:
I would suggest getting ride of the id on your button or make them unique.
Change document.getElementById('UserLink') to this and that will get you the button that was clicked.

RadioButtonList checked with javascript

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>

set value of dropdown lists in Gridview with javascript

I have a dropdownlist and a gridview with a drop down list in every row. I have removed other cols in Grid for simplicity.
Whenever a new value in the dropdownlist is selected I would like to set all of the dropdownlists in the gridview to that same value via javascript. (Yea both the dropdownlist outside the gird and the ones inside the grid are populated by the same data source)
The dropdownlist:
<asp:DropDownList onchange="javascript:onJDSelection();" ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource4" DataTextField="circt_cstdn_nm"
DataValueField="circt_cstdn_user_id">
</asp:DropDownList>
The GridView:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" onrowdatabound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Change to Job Designer" SortExpression="circt_Cstdn_nm">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("circt_Cstdn_nm") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddl_jd" runat="server" DataSourceID="SqlDataSource4" DataTextField="CIRCT_CSTDN_NM"
DataValueField="CIRCT_CSTDN_user_id"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My current attempt:
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var grid = document.getElementById('ctl00_MAIN_GridView2');
for (var i = 1; i < grid.rows.length; i++) {
grid.rows[i].cells[0].getElementsByTagName("*")[1].selectedText = jd;
}
}
any ideas?
Thanks!
Update: I tried this.
<script type="text/javascript">
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var dropDowns = jQuery('input[id^=ctl00_MAIN_GridView2_ddl_jd]');
alert("test");
alert(dropDowns);
var i = 0;
dropDowns.each(function () {
alert(i);
i++;
jQuery('#' + jQuery(this) + ':first-child').text(jd);
});
}
</script>
When clicking on the dropdown I get an alert that says "test" and an alert that says "[Object object]" However nothing happens with the dropdowns in the grid and the alert(i) never fires.
I suggest to change the selected values for the dropdownlists from code behind like this:
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in GridView2.Rows)
{
Control ctrl = gvRow.FindControl("ddl_jd");
DropDownList ddl = ctrl as DropDownList;
if (ddl != null)
ddl.SelectedIndex = DropDownList3.SelectedIndex;
}
}
Also make sure to set AutoPostBack="true" for DropDownList3.
Another approach (that is not very clean or simple) is to add the following code into the Page_Load method (and remove the script block containing onJDSelection function from the .aspx file):
if (!Page.IsPostBack)
{
string functionContent = "<script language=javascript> function onJDSelection()" +
"{ var selectedIndex = document.getElementById('" + DropDownList3.ClientID + "').selectedIndex;" +
"var grid = document.getElementById('" + GridView2.ClientID + "'); " +
"for (var i = 1; i < grid.rows.length; i++) " +
"{ var selObj = grid.rows[i].cells[0].getElementsByTagName(\"*\")[0]; selObj[selectedIndex].selected = true;} "+
"}</script>";
Page.RegisterStartupScript("MyScript", functionContent);
DropDownList3.Attributes.Add("onchange", "onJDSelection()");
}.
Note that is this case the ID used for retrieving DropDownList3 and GridView2 in javascript are sent from code behind as is not very safe to rely on server control ID's generated by ASP .NET. In case you want to save the dropdownlists values (that are changed using javascript) you will also need additional code.
It works based on the following body for aspx page:
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource1" DataTextField="circt_cstdn_nm"
DataValueField="circt_cstdn_user_id" onselectedindexchanged="DropDownList3_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
onrowdatabound="GridView2_RowDataBound" DataKeyNames="circt_cstdn_user_id">
<Columns>
<asp:TemplateField HeaderText="Change to Job Designer" SortExpression="circt_Cstdn_nm" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("circt_Cstdn_nm") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddl_jd" runat="server" DataSourceID="SqlDataSource1" DataTextField="CIRCT_CSTDN_NM"
DataValueField="CIRCT_CSTDN_user_id"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [test]"></asp:SqlDataSource>
</div>
</form>
If possible, I'd suggest that you use jQuery. It has a multitude of partial name selectors and input selectors that you can use to get all of your DropDowns. You could use something like:
function onJDSelection() {
var jd = document.getElementById('ctl00_MAIN_DropDownList3').Text;
var dropDowns = jQuery('input[id^=ctl00_MAIN_GridView2_ddl_jd]');
dropDowns.each(function() {
jQuery('#' + jQuery(this) + ':first-child').text(jd);
});
}

Categories