I want specific row dropdown to be shown when the same row's checkbox is selected. But having problem as all the dropdowns of the grid are shown on one row's checkbox selection.
This is the Grid:
<asp:TemplateField HeaderText="Advertise Id" HeaderStyle-Width="150px" HeaderStyle-Font-Size="14px" HeaderStyle-ForeColor="Black">
<ItemTemplate>
<div style="text-align: left;">
<asp:TextBox runat="server" Width="120px" ReadOnly="true" ID="TextBoxAdvertiseId" Text='<%# Eval("AdvertiseIdName")%>' />
<input type="checkbox" class="CheckBoxImage" onclick="CheckBoxImage()" />
<asp:DropDownList CssClass="DDAdvertise" runat="server" Width="130px" ID="drpdwnadvertiseAdd"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
This is the jquery Code:
function CheckBoxImage() {
var flag = false;
$('.GridLocation input[type="checkbox"]').each(function () {
var checkbox = $('.GridLocation input[type="checkbox"]');
var row = $(this).parent().parent().parent().parent().parent();
if ($(this).is(':checked')) {
flag = true;
$(row).find('.DDAdvertise').show(); // Problem is in .DDAdvertise as it is a classname so it's selecting all the dropdowns
} else {
$(row).find('.DDAdvertise').hide();
}
if (flag) {
$(row).find('.DDAdvertise').show();
}
else {
$(row).find('.DDAdvertise').hide();
}
});
}
Now, the problem is i am using class name (.DDAdvertise) in jquery which is showing all the dropdowns. I want the specific dropdown to be shown whose row's checkbox is selected.
Related
I have spent several days looking at various resources and am getting more confused. I have several controls in a .aspx file: an edit button, a year dropdownlist, and four gridviews with textboxes and dropdownlists in them. The textboxes and dropdownlists in the gridviews start disabled. When the user clicks the edit button, they should enable. This works the first time, but they won't disable again. Here's the relevant code:
private void toggleEditMode()
{
editBtn.CssClass = editBtn.Attributes["mode"].ToString() == "edit" ? "btn btn-success" : "btn btn-primary";
editBtn.Text = editBtn.Attributes["mode"].ToString() == "edit" ? "<span class='glyphicon glyphicon-floppy-disk'></span> Save" : "<span class='glyphicon glyphicon-edit'></span> Edit";
editBtn.Attributes["mode"] = editBtn.Attributes["mode"].ToString() == "edit" ? "save" : "edit";
selectYear.Enabled = !selectYear.Enabled;
foreach (GridView gv in panels)
{
foreach (GridViewRow gvr in gv.Rows)
{
TextBox name = (TextBox)gvr.FindControl("nameTB");
DropDownList rating = (DropDownList)gvr.FindControl("ratingDDL");
name.Enabled = !name.Enabled;
rating.Enabled = !rating.
}
}
}
The edit button turns into the save button properly, and the year dropdownlist toggles correctly, but the textboxes and dropdownlists in the gridview won't disable. During debugging, I have discovered that the Enabled property of each textbox and DDL is false at the beginning of this method.
The textboxes and DDL's all start disabled, enable on the button click, and then won't disable, even though the button and year DDL toggle correctly.
My question is: how exactly does the Enabled property work? Any help is greatly appreciated.
EDIT: here is the markup:
<asp:LinkButton ID="editBtn" runat="server" ClientIDMode="Static" OnClick="ToggleEditMode" CssClass="btn btn-primary" mode="edit">
<span class="glyphicon glyphicon-edit"></span> Edit
</asp:LinkButton>
<div class="form-inline" role="form">
<fieldset>
<div class="form-group">
<label for="selectYear">Year: </label>
<asp:DropDownList ID="selectYear" runat="server" CssClass="form-control" AutoPostBack="true" ClientIDMode="Static"></asp:DropDownList>
</div>
</fieldset>
</div>
And here is the gridview:
<asp:GridView ID="jrSchools1a2aAdmin" runat="server" AutoGenerateColumns="false" GridLines="None" ClientIDMode="Static" OnRowCreated="BindRatings" CssClass="table table-striped table-bordered">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="nameTB" runat="server" Text='<%# Eval("name") %>' ClientIDMode="Static" schoolID='<%# Eval("schoolID") %>' Enabled="false" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:DropDownList ID="ratingDDL" runat="server" SelectedValue='<%# Eval("rating") %>' ClientIDMode="Static" Enabled="false" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="students" HeaderText="Students" />
<asp:BoundField DataField="7_1" HeaderText="7-I" />
<asp:BoundField DataField="7_2" HeaderText="7-II" />
<asp:BoundField DataField="8_1" HeaderText="8-I" />
<asp:BoundField DataField="8_2" HeaderText="8-II" />
<asp:BoundField DataField="open" HeaderText="Open" />
<asp:BoundField DataField="score" HeaderText="Score" />
</Columns>
</asp:GridView>
ToggleEditMode checks if it should save or not, runs a SQL query if it should save, and calls toggleEditMode().
EDIT 2: Here is where toggleEditMode() is called. Sorry for the confusion. It's not called anywhere else.
protected void ToggleEditMode(object sender, EventArgs e)
{
if (editBtn.Attributes["mode"].ToString() == "save")
{
StringBuilder query = new StringBuilder();
List<SQLParameter> parameters = new List<SQLParameter>();
//Determine the year
int year;
int.TryParse(selectYear.SelectedItem.Value, out year);
parameters.Add(new SQLParameter("#year", year));
// Use a counter so we can enumerate parameter names
int i = 0;
foreach (GridView gv in panels)
{
foreach (GridViewRow gvr in gv.Rows)
{
TextBox name = (TextBox)gvr.FindControl("nameTB");
DropDownList rating = (DropDownList)gvr.FindControl("ratingDDL");
name.CssClass = "form-control green";
//SQL statements here
parameters.Add(new SQLParameter(String.Format("#name{0}", i), name.Text));
parameters.Add(new SQLParameter(String.Format("#schoolID{0}", i), name.Attributes["schoolID"].ToString()));
parameters.Add(new SQLParameter(String.Format("#rating{0}", i), rating.SelectedValue));
i++;
}
}
SqlConn.doQuery(query.ToString(), parameters);
//populateTables();
}
toggleEditMode();
}
Like #mjw mentioned in the comments, I was setting Enabled='false' in the markup. Due to the page life cycle, the controls were always rendering as Enabled='false'. If controls can be enabled/disabled based on conditions, this is best handled in the Page_Load function. However, ASP.NET has editing capabilities built into the GridView control, and these should be preferred over AJAX submissions for the inherent security benefits built into ASP.NET. Here are some links to get you started:
Making a column editable in an ASP.net GridView
https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms972948(v=msdn.10)
I am trying to validate a drop down inside a gridview on a button click. If the drop down has no selection then i want to fire the javascript but the code is not firing at all. I am not sure what am i doing wrong here so please help. thanks.
Here is the button code in the aspx file:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px" Visible="true"
onclick="btnSubmit_Click"
OnClientClick="return validate();"
Font-Bold="True" Font-Size="Medium" Height="30px"
style="margin-right: 1px; margin-left: 185px;" ForeColor="#336699" />
here is the javascript in the head section of my page:
<script type="text/javascript">
function validate() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('--'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == '--') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select value in each dropdown');
}
return flag;
}
</script>
here is my drop-down in the aspx:
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
here is the code behind for the dropdown
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
ddl_Answer.Items.Insert(0, new ListItem("--"));
How are you trying to select the dropdown using javascript. You probably want this
dropdowns = gridview.getElementsByTagName('select');
First of all what I want to do is to pre select a value in my RadComboBox ,and if this value is not selected something else is selected then change the visibility to of some specific fields hidden.
My problem is that I'm able to make my pre select but somehow I can not change the status of my visibility for my specific fields when this pre selected value has changed.
What I have tired is to do it with a standard event OnSelectedIndexChanged but some how this is not triggering why so ever.. I have also added AutoPostBack=true as well as ViewStateMode=Enabled"
First my field's
Here comes my preslect as well here I would like to trigger the visibility change
<div class="formRowDiv">
<asp:Label ID="Activitylbl" runat="server" Text="Activity" CssClass="formLabel" />
<telerik:RadComboBox ID="rcbActivity" CssClass="rowForm" ViewStateMode="Enabled" runat="server" Width="260px" EmptyMessage="- Activity -"
DataTextField="ActivityId" DataValueField="ActivityId" AutoPostBack="true" OnSelectedIndexChanged="rcbActivity_SelectedIndexChanged">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ControlToValidate="rcbActivity"
ErrorMessage="Can not be empty" CssClass="rowFormValidation" />
</div>
What I want to hide:
<div class="formRowDiv">
<asp:Label ID="ActivityDescription" runat="server" Text="ActivityDescription" CssClass="formLabel" Visible="false"/>
<telerik:RadTextBox runat="server" ID="rtbActivityDescription" Wrap="true" Height="50" TextMode="MultiLine" AutoPostBack="true" CssClass="rowForm" ReadOnly="true" Visible="false" />
</div>
How I do my pre selection :
In my databind method that is called in my Page_Load
I firrst loop and then do a pre select
foreach (Activity item in ctx.Activity.OrderBy(l =>l.Code))
{
rcbActivity.Items.Add(new RadComboBoxItem(item.FullActivity, item.ActivityId.ToString()));
if (rcbActivity.Items.FindItemByValue("4") != null)
{
rcbActivity.SelectedIndex = rcbActivity.Items.IndexOf(rcbActivity.Items.FindItemByValue("4"));
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
}
Here is how I would hide my Fields
protected void rcbActivity_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
In case your controls are in an update panel then try removing it if the update panel is not so important and see if the changes u make to the controls in the server side are getting affected properly
I hava a datalist in side that I have checkbox
<asp:DataList ID="dlst1" runat="server" RepeatDirection="Horizontal" OnItemDataBound="dlst1_ItemDataBound" CaptionAlign="Left">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" />
<asp:Label ID="lbl" runat="server"/>
<asp:CheckBox ID="Chkbox" runat="server" TextAlign="Right" />
</ItemTemplate>
</asp:DataList>
I have 2 button
I want to check all the check box when user click on Check All btn, and Uncheck All checkbox when user click on Uncheck All btn, I don't want any post back, how to do it in client side.
I am trying
function CheckOrUncheckAll(isChecked) {
var dataList = document.getElementById('<%= DataList.ClientID %>');
for (var index = 0; index < dataList.rows.length; index++) {
for (var cIndex = 0; cIndex < dataList.rows[index].cells.length; cIndex++) {
dataList.rows[index].cells[cIndex].childNodes[3].checked = isChecked;
}
}
return false;
}
<asp:Button ID="btnCheckAll" runat="server" Text="Check All" OnClientClick="return CheckOrUncheckAll(true)" />
<asp:Button ID="btnUnCheckAll" runat="server" Text="Uncheck All" OnClientClick="return CheckOrUncheckAll(false)" />
its working fine but I don't want to use childNodes[3], because in future in in datalist something got added then I need to change the index.. any jquery to change this function
please try below
function CheckUnCheckAll(checkoruncheck)
{
var list = document.getElementById("<%=dlst1.ClientID%>") ;
var chklist = list.getElementsByTagName("input");
for (var i=0;i<chklist.length;i++)
{
if (chklist[i].type=="checkbox" )
{
chklist[i].checked = checkoruncheck;
}
}
}
call this as
CheckUnCheckAll(true);
or
CheckUnCheckAll(false);
I think, you must use jQuery.
To check:
$("#<%=btnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").attr("checked", "checked");
});
To uncheck:
$("#<%=btnUnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").removeAttr("checked");
});
I want to get the value of check box placed inside grid view. if check box is checked, it textbox in that row should be enable and if it is again uncheked, the textbox should get clear and disabled. I asked this question few hours back but still didn't get satisfactory answer.
I tried like this.
//My grid code.
<asp:GridView ID="DeptGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="DeptId" HeaderText="ID"/>
<asp:BoundField DataField="DeptName" HeaderText="Department"/>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="addToCompanyBox" onClick="EnableHODBox()" runat="server" />
</ItemTemplate>
<HeaderTemplate>
Add
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hodNameBox" runat="server" Width="200px" Enabled="false"></asp:TextBox>
</ItemTemplate>
<HeaderTemplate>
Dept Head
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//My javascript code
<script type="text/javascript">
function EnableHODBox() {
//alert('hello');
var GridView = document.getElementById('<%=DeptGrid.ClientID %>');
//var GridView = document.getElementById('');
var DeptId;
if (GridView.rows.length > 0) {
for (Row = 1; Row < GridView.rows.length; Row++) {
// DeptId = GridView.rows.cell[0];
if (GridView.rows[Row].cell[3].type == "checkbox")
// var chkbox = GridView.rows[Row].cell[3].type == "checkbox"
(GridView.rows[Row].cell[3].type).checked = true;
}
}
}
</script>
This solution is tested and works using only JavaScript (no jQuery is required for this solution!).
1. C# Part (In Page_Load Method)
In Page_Load we need to add a small hack:
foreach(GridViewRow row in YourGridViewControlID.Rows)
{
if (row.RowType == DataControlRowType.DataRow )
{
((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");");
}
}
This way, we are adding the JavaScript function call on the OnChange event of every CheckBox of our GridView. What is special and we can't achieve through the HTML is that we are passing the Row Index of each one in the JavaScript function, something that we need later.
2. Some important notes for the HTML Part
Make sure that both Checkbox control and Textbox control but more importantly your GridView Control has static id by using the ClientIDMode="Static" as shown bellow:
<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />
And for the GridView control:
<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">
3. Javascript Part
And then in your JavaScript file/code:
function TextboxAutoEnableAndDisable(Row) {
// Get current "active" row of the GridView.
var GridView = document.getElementById('YourGridViewControlID');
var currentGridViewRow = GridView.rows[Row + 1];
// Get the two controls of our interest.
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
// If the clicked checkbox is unchecked.
if( rowCheckbox.checked === false) {
// Empty textbox and make it disabled
rowTextBox.value = "";
rowTextBox.disabled = true;
return;
}
// To be here means the row checkbox is checked, therefore make it enabled.
rowTextBox.disabled = false;
}
4. Some Notes for the above implementation
Note that in the JavaScript code, at the line:
var currentGridViewRow = GridView.rows[Row + 1];
the [Row + 1] is important to make this work and should not change.
And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
The .cells[2] and .cells[0] is maybe different for you, so you have to choose the correct number in the [].
Usually, this will be the column number of your GridView starting counting from 0.
So if your CheckBox was in the first column of the GridView then you need .cells[0].
If your TextBox is in the second column of your GridView then you need .cells[1] (in my case above, TextBox was in the third column of my GridView and therefore, I used .cells[2])
You can use the onclick JavaScript instead of the OncheckedChanged event which is a CheckBox server side event.
<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />
Edit:
var GridView = document.getElementById('<%=DeptGrid.ClientID %>')
Edit: Upon your request in comment
if (GridView.rows[Row].cell[2].type == "checkbox")
{
if (GridView.rows[Row].cell[2].childNodes[0].checked)
{
GridView.rows[Row].cell[3].childNodes[0].disabled=false;// Enable your control here
}
}
I also found that the statement if (GridView.rows[Row].cell[2].type == "checkbox") results in an error, GridView.rows[Row].cell[2].type is undefined. The code I have running now is as follows:
var grid = document.getElementById('<%=grdResults.ClientID%>');
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
if (grid.rows[row].cells[0].childNodes[0].checked) {
// do something here
alert('function for row ' + row);
}
}
You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
Hi here you are having very easy Solution
Suppose your grid is like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="64px"
Width="389px" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="EmployeeId">
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF66FF" ForeColor="#660033" />
</asp:GridView>
and your javascript to find controls inside your grid is
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnAddToGrid").click(function () {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
var employeeId = $row.find("span[id*='lblEmployeeId']").text();
var firstname = $row.find("span[id*='lblFirstName']").text();
var lastname = $row.find("span[id*='lblLastName']").text();
alert("ID :" + employeeId +"\n" + "Name :" + firstname +" "+ lastname );
});
});
</script>
Find controls inside the grid using java script:
for (var r = 1; r < grid.rows.length; ++r) {
var indexValue = 0; //based on browser. //IE8
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
if (typeof (txtPeriod.value) == "undefined")//IE9
indexValue = 1
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
alert(txtPeriod.value);
}
var x = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
var i;
var cnt = 0;
for (i = 0; i < x.length; i++) {
if(x[i].type== "checkbox" && x[i].checked)
cnt++;
}
alert("item selected=" + cnt);