How to Uncheck All Radio Button inside GridView using JQuery? - c#

I have a Radio Button inside GridView. I want to Uncheck all the asp.net Radio Button except the current Selected one using JQuery. I have tried but no results..!
HTML Markup:
<ItemTemplate>
<asp:RadioButton ID="rdbUser" runat="server" kID='<%# Eval("kID")%>' class="rdbUser" />
</ItemTemplate>
Code:
$(document).on("click", ".rdbUser", function() {
var selectedRadio = $(this).attr('id');
//var newrdo = $("input:radio.rdbUser:checked");
//$(".rdbUser").prop('checked', false);
//$('#' + selectedRadio).prop('checked', true);
//$('input:radio[class=rdbUser]').prop('checked', false);
// $('.rdbUser').removeAttr('checked');
var kID = $(this).attr('kID');
$("#ctl00_ContentPlaceHolder1_hdnKioskID").val(kID);
alert("selected Radio : " + kID);
});
On SeeingMarkup in Chrome:
Checked RadioButton:
<span class="rdbUser" kid="2"><input id="ctl00_ContentPlaceHolder1_GridView1_ctl03_rdbUser" type="radio" name="ctl00$ContentPlaceHolder1$GridView1$ctl03$rdbUser" value="rdbUser"></span>
Unchecked RadioButton:
<span class="rdbUser" kid="21"><input id="ctl00_ContentPlaceHolder1_GridView1_ctl05_rdbUser" type="radio" name="ctl00$ContentPlaceHolder1$GridView1$ctl05$rdbUser" value="rdbUser"></span>

Try this,
$(document).on("click", ".rdbUser", function() {
// to uncheck all radios which are not checked
$("input[type=radio].rdbUser").prop("checked", false);
$(this).prop('checked',true);// check the current one only
});

I think you should use RadioButton.GroupName property.
Use the GroupName property to specify a grouping of radio buttons to create a mutually exclusive set of controls. You can use the GroupName property when only one selection is possible from a list of available options.
When this property is set, only one RadioButton in the specified group can be selected at a time.
However you can try this code using jquery
$(document).on("click", ".rdbUser", function() {
//Check if this radio button is checked
if($(this).find("input[type=radio]").is(':checked'))
{
//Use .not() to exclude this
//Use .prop() to set checked to false
$(".rdbUser").not(this).find("input[type=radio]").prop("checked", false);
}
});

Use change event instead of click
IF using jquery version > 1.6 use prop else use attr
$(".rdbUser").change(function(){
if($(this).prop("checked")){
$("[id^='rdbUser']").not(this).prop("checked",false);
}
});

Hope this helps!. 'grdOrganization' is the Id of GridView.
<script type="text/javascript">
function ResetRadioBtns(rb) {
var gv = document.getElementById("<%=grdOrganization.ClientID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
</script>
<asp:TemplateField ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:RadioButton ID="rbtnMaster" runat="server" onclick="ResetRadioBtns(this)" />
</ItemTemplate>
</asp:TemplateField>

Related

Is it possible to go to next and previous rows using Grid View?

Is there a way to navigate between rows and get the row data if i have two buttons called Next and Previous. By Clicking on Next Button i get the next row data and highlight the row and previous row data on the Previous Button.
I am using ASP.NET 2.0 GridView.
int CurrentIndex = GridView1.SelectedIndex;
if (CurrentIndex != GridView1.Rows.Count - 1){
int NextRowIndex = GridView1.Rows[GridView1.SelectedIndex + 1].RowIndex;
GridView1.SelectedIndex = NextRowIndex;
//get info
}
Try like that way
You can achieve it using javascript only which is very fast as page doesn't do post back every time you change row.
Assume simple version of page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<asp:Button ID="btnPrevious" runat="server" Text="Prev" OnClientClick="changeSelectedRow(-1)" />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClientClick="changeSelectedRow(1)" />
<br />
<br />
Sample form with 2 boxes:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Then this simple javascript will do the work:
<script type="text/javascript">
var selectedRow;
$(document).ready(function () {
var rows = $('#' + '<%= GridView1.ClientID %>').find('tr');
// select first row by default
rows.get(1).style.backgroundColor = '#0000AA';
selectedRow = 1;
document.getElementById('<%= TextBox1.ClientID %>').value = rows.get(selectedRow).childNodes[0].innerText;
document.getElementById('<%= TextBox2.ClientID %>').value = rows.get(selectedRow).childNodes[1].innerText;
});
function changeSelectedRow(step) {
var rows = $('#' + '<%= GridView1.ClientID %>').find('tr');
var newSelectedRow = selectedRow + step;
if (newSelectedRow > 0 && newSelectedRow < rows.length) {
rows.get(selectedRow).style.backgroundColor = '#ffffff';
rows.get(newSelectedRow).style.backgroundColor = '#0000aa';
selectedRow = newSelectedRow;
document.getElementById('<%= TextBox1.ClientID %>').value = rows.get(newSelectedRow).childNodes[0].innerText;
document.getElementById('<%= TextBox2.ClientID %>').value = rows.get(newSelectedRow).childNodes[1].innerText;
}
// stop postback
event.returnValue = false;
return false;
}
</script>
Above requires jquery to work. Instead of background color you can set 'className' to be your highlighet/normal row class.
How are you binding the data? (object datsource, sql datasource, datasource/databind, etc.) If you want the actual data that was used to bind the gridview you will need to get it from the datasource.
gv.Rows[row].Cells[col]
will give you what is displayed in the selected gridview row but that is going to include whatever your template shows and not just the data.
One solution would be to pass the primary key as a command argument of the select button in the gridview and then when you select the gridview it searches the datatable for that record and then you can display that data in textboxes, etc.
Add select btn col to gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnSelect" Text="Select" CommandName="Select" CommandArgument='<%#Eval("Month")%>'/>
</ItemTemplate>
</asp:TemplateField>
Add to gridview:
OnRowCommand="gvReport_OnRowCommand"
Textbox:
<asp:TextBox runat="server" ID="txtPerson" />
Codebehind:
In this example "Month" is unique in my data, SessionDataTbl is a data table that i used to bind the gridview with.
protected void gvReport_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//Find row data
foreach (DataRow row in SessionDataTbl.Rows)
{
if (row["Month"].Equals(e.CommandArgument))
{
txtPerson.Text = row["Person"].ToString();
//other text boxes, etc.
break;
}
}
//Add row color change
Button btn = e.CommandSource as Button;
if (btn != null)
{
System.Web.UI.Control field = btn.Parent;
if (field != null)
{
GridViewRow row = field.Parent as GridViewRow;
if (row != null)
{
const string backColor = "background-color";
//Remove any previous backcolor
foreach (GridViewRow rw in gvReports.Rows)
{
rw.Style.Remove(backColor);
}
row.Style.Add(backColor, "yellow");
}
}
}
}
}
This example uses manual databinding but this could also be done using an objectdatasource, etc. but you would have to capture the datatable in the object datasource Selected event (can provide an example if needed)
Note: must have gridview viewstate enabled for this example
I would try something like this,
//variables used
int currentrow = 0;
int maxrow = dataGridView1.Rows.Count-1;
//on gridview fill
for(int i=0;i<dataGridView1.Rows.Count;i++)
{
dataGridView1.Rows[i].Visible = false;
}
currentrow=0;
ataGridView1.Rows[0].Visible = true;
//button next
if (currentrow < maxrow)
{
dataGridView1.Rows[currentrow].Visible = false;
currentrow++;
dataGridView1.Rows[currentrow].Visible = true;
retrieveData();
}
//button previous
if (currentrow > 0)
{
dataGridView1.Rows[currentrow].Visible = false;
currentrow--;
dataGridView1.Rows[currentrow].Visible = true;
retrieveData();
}
//retrieveData(); would be calling the void
//that fills the textboxes with the dataGridView data;
I think something like this should work to cycle through the rows, I can't guarantee that it't all typed 100% correct since some of it was typed on SO in the textbox.

Why is LinkButton not executing the Click function from code behind

I have a GridView which has these two controls:
<asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' OnClick="btnShow_Click" />
<asp:LinkButton runat="server" ID="btnShow2" CssClass="btnSearch2" Text="View Allst" CommandName="ViewAll" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' PostBackUrl="JavaScript:void(0);" OnClientClick="return false;" OnClick="btnShow_Click">View Alls</asp:LinkButton>
code-behind:
protected void btnShow_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Button btn1 = (System.Web.UI.WebControls.Button)(sender);
string strCA = btn1.CommandArgument;
string strCN = btn1.CommandName;
int index = 0;
if (strCN == "ViewAll")
{
index = Convert.ToInt32(strCA);
DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
string column = cacheTable.Rows[index].Field<string>("Guideline");
string test = BookingResults.Rows[index].Cells[7].Text;
string html = HttpUtility.HtmlDecode(column);
ResultsDiv.InnerHtml = html;
}
}
JQuery:
$(document).ready(function () {
//Click the button event!
$(".btnSearch").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$(".btnSearch2").click(function (e) {
e.preventDefault();
alert($(this).val() + " Clicked");
//centering with css
centerPopup();
//load popup
loadPopup();
});
$("#popupContactClose").click(function () {
disablePopup();
});
$("#backgroundPopup").click(function () {
disablePopup();
});
//Press Escape event!
$(document).keypress(function (e) {
if (e.keyCode == 27 && popupStatus == 1) {
disablePopup();
}
});
});
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup() {
//loads popup only if it is disabled
if (popupStatus == 0) {
$("#backgroundPopup").css({
"opacity": "0.7"
});
$("#backgroundPopup").fadeIn("slow");
$("#popupContact").fadeIn("slow");
popupStatus = 1;
}
alert(popupStatus);
}
//disabling popup with jQuery magic!
function disablePopup() {
//disables popup only if it is enabled
if (popupStatus == 1) {
$("#backgroundPopup").fadeOut("slow");
$("#popupContact").fadeOut("slow");
popupStatus = 0;
}
alert(popupStatus);
}
//centering popup
function centerPopup() {
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
//centering
$("#popupContact").css({
"position": "absolute",
"top": windowHeight / 2 - popupHeight / 2,
"left": windowWidth / 2 - popupWidth / 2
});
//only need force for IE6
$("#backgroundPopup").css({
"height": windowHeight
});
}
HTML that displays the popup:
<div id="popupContact">
<a id="popupContactClose" title="Close Window">x</a>
<h3>Booking Guidelines</h3>
<asp:Panel ID="Panel1" runat="server" style="vertical-align:top" ScrollBars="Vertical" Height="300px" ForeColor="Black">
<div id="ResultsDiv" runat="server" style="vertical-align:top" > </div>
</asp:Panel>
</div>
<div id="backgroundPopup"></div>
The GridView generates multiple rows, where each row the button will have a different INDEX number to reference the session table being used to populate ResultsDiv.InnerHtml = html;.
When I click on btnShow Button it displays the alert and shows the popup with the updated ResultsDiv.InnerHtml = html; by using the code-behind for a split second and does a postback and reloads the page.
When I click 'btnShow2' LinkButton it displays the alert and shows the popup and does not do a postback. The only issue I am having is, it doesn't access the code-behind to update ResultsDiv.InnerHtml = html; so it is always displaying the same result no matter what row the button is clicked.
How do I modify my code so that it updates the ResultsDiv.InnerHtml = html; and displays the popup every time the button is clicked on any of the row and does NOT do a postback?
If You Remove Both
OnClientClick="return false;" and
PostBackUrl="JavaScript:void(0);" then definitely it will postback.
You can observe your HTML generated/rendered if you set both attributes with Postback event
WebForm_DoPostBackWithOptions which should be something like
javascript:__doPostBack('BookingResults$ctl02$btnShow2','')
View Alls
You have OnClientClick="return false;". That cancels the postback. To fix it, remove that attribute from your LinkButton declaration.
Also, not sure what PostBackUrl="JavaScript:void(0);" does. I've never seen someone to do that. You might try eliminating that if it's not necessary.

how to count number of checkboxes(across all pages of gridview) checked in gridview using javascript

I am in a situation where in need help from you.
i have written below code in javascript which checks how many checkboxes are checked in gridview and display message however its restricted to one page of my gridview only and doesnt work when i move to next page, is there any way that javascript code check how many checkboxes have been checked across all pages of gridview ?
function CheckBoxCount()
{
var gv = document.getElementById("<%= Gridview1.ClientID %>");
var inputList = gv.getElementsByTagName("input");
var numChecked = 0;
for (var i = 0; i < inputList.length; i++)
{
if (inputList[i].type == "checkbox" && inputList[i].checked)
{
numChecked = numChecked + 1;
if( numChecked > 8)
{
alert('Only Eight items could be added in final grid');
break;
}
}
}
}
alert($('input[name=checkbox_name]').attr('checked'));
or
alert($("input:checkbox:checked").length);
if they didnt work check this : calculate the number of html checkbox checked using jquery
*** dont forget to add Jquery.min.js in your markup
Try the bellow code:
Javascript:
function gvCheckBoxClick(currentCheck) {
var input = document.getElementById("<%=gvRuleList.ClientID %>");
var chekRowCount = document.getElementById("<%=chkRowCount.ClientID %>").value;
if (currentCheck.type == "checkbox") {
if (currentCheck.checked == true) {
chekRowCount++;
}
else {
chekRowCount--;
}
}
}
Gridview:
<Columns>
<asp:TemplateField HeaderText="<%$ Resources:Opm_RuleList_ListHeader_Select %>">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" onclick="javascript:gvCheckBoxClick(this);"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
use hidden variable
<input type="hidden" id="chkRowCount" name="chkRowCount" runat ="server" value="0" />

SelectAll in gridview using javascript on postback issue

i have a gridview which has a checkbox column. The header is of this column is a checkbox.
When it is checked all the values get checked and vice-verse.
I do this using javascript.
The problem is if i check it and perform any other event on the page which requires a postback the checked values disappear. I dont want them to disappear.
here is my code:
<script type="text/javascript">
function checkAllBoxes() {
//get total number of rows in the gridview and do whatever
//you want with it..just grabbing it just cause
var totalChkBoxes = parseInt('<%= GridView1.Rows.Count %>');
var gvControl = document.getElementById('<%= GridView1.ClientID %>');
//this is the checkbox in the item template...this has to be the same name as the ID of it
var gvChkBoxControl = "Select_CheckBox";
//this is the checkbox in the header template
var mainChkBox = document.getElementById("chkBoxAll");
//get an array of input types in the gridview
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
</script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Select_CheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<!-- The rest of your rows here -->
</Columns>
</asp:GridView>
Thanks for the help.
Make your checkbox a server-side control that uses the view state by adding runat="server". It will then maintain its value across post backs.
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/>
And change your JavaScript to select the id that ends in chkBoxAll. I use jQuery in the example below:
//this is the checkbox in the header template
var mainChkBox = $('input[id$="chkBoxAll"]');
However, if you sort your gridview rows or use paging, you will likely come across less friendly behavior.

Retrieve a TextBox using JavaScript

I have a GirdView in Edit Mode with inside a TextBox.
I need to Retrieve this TextBox with ID (from the source code in the browser) in JavaScript.
ctl00$MainContent$uxListOptions$ctl02$uxValueInput
But I receive an error because my JavaScript is not able to find the TextBox.
Here is the code:
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span>
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
I am trying to use this code http://dustyreagan.com/how-to-submit-html-without-disabling/
Any Idea what am I doing wrong? Thanks guys!
If you are using ASP.Net 4.0, you could use ClientIdMode=Static or Predictable for this control.
encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')
This will result in
encodeMyHtml('ctl00_MainContent_uxListOptions_ctl02_uxValueInput_FormViewContentManager_ContentTextBox')
Does a control of that ID exist in your DOM?
It seems that you're making a lot of assumptions as to how the ID's will be created. It would be better to immediately reference the ContentTextBox.ClientID.
Something like the following, provided that ContentTextBox is a valid reference to the text box:
encodeMyHtml('<%# ContentTextBox.ClientID %>')
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);
}

Categories