Asp.net multiple gridviews, checkboxes in headertemplate select all / deselect all functionality - javascript

I am using two gridview controls in my aspx page. And I have a column of checkbox in both my controls. I am facilitating the user to select/deselect all checkboxes in my both gridviews by providing a checkbox in the header template of both gridviews and using java script functions. below is the code
<script type="text/javascript">
function UncheckParent(obj) {
var isUnchecked = obj.checked;
if (isUnchecked == false) {
var frm = document.forms[0];
for (i = 0; i < frm.length; i++) {
if (frm.elements[i].id.indexOf('chkSelectAllCheckboxes') != -1) {
frm.elements[i].checked = false;
}
}
}
}
function CheckAll(obj) {
var row = obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
var inputs = row.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
inputs[i].checked = obj.checked;
}
}
}
</script>
But the problem is that once i select or deselect one of such checkboxes all checkboxes in both the gridviews get checked. I can also give a short example of what is happening. Two gridviews gdvwStudents and gdvwTeachers. Both have checkbox column and a check box in header template. using above code when I click header checkbox of gdvwStudents, all checkboxes in gdvStudents and gdvTeachers get selected. Please

You are doing it wrong. You should be getting the check boxes inside the particular grid where the header is clicked; instead, you are getting ALL the checkboxes created on the form! That's incredibly inefficient and explains why everything is checked/unchecked regardless of which header you click.
If you can use jQuery, you should be able to rewrite those functions into something like this:
function checkAll(gridID,checkbox) {
$("#"+gridID+" input:checkbox").attr("checked",checkbox.checked);
}
See this jsfiddle for a quick example.

Add the javascript function as per below
<script type="text/javascript">
function SelectAll(id, grd) {
//get reference of GridView control
var grid = null;
if (grd = "1") {
grid = document.getElementById("<%= GridView1.ClientID %>");
}
else {
grid = document.getElementById("<%= GridView2.ClientID %>");
}
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0) {
//loop starts from 1. rows[0] points to the header.
for (i = 1; i < grid.rows.length; i++) {
//get the reference of first column
cell = grid.rows[i].cells[0];
//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
and handle Rowbound event of gridviews bind call of javascript function as per below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "'" + ", '1')" );
}
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "'" + ", '2')" );
}
}

This is how I managed it:
function UnCheckAllContainer(obj) {
var isUnchecked = obj.checked;
if (isUnchecked == false) {
var frm = document.forms[0];
for (i = 0; i < frm.length; i++) {
if (frm.elements[i].id.indexOf('chkSelectAllCheckboxesContainers') != -1
) {
frm.elements[i].checked = false;
}
}
}
}
function CheckAllContainer(chk) {
$('#<%=gdvwContainers.ClientID %>').find("input:checkbox").each(function () {
if (this != chk) {
this.checked = chk.checked;
}
});
}

Related

Explain the program logic in javascript to make a single checkbox selected when all other checkboxes are selected

function check(){
var xx =document.getElementById("of");
var box = document.getElementsByName("chk");
for(var i=0 ; i<box.length;i++){
if(box[i].checked == true){
x=x+1;
}
if (x == box.length){
xx.checked = true;
}
}
}
Here check is the onclick function of checkboxes that is selected by the user.The name of the checkboxes are "chk".
Here "xx" represent the checkbox that want to be selected automatically when all other checkboxes are select
Welcome to Stack Overflow.
In the future, please do basic research and read "How to ask a question" before posting your question here.
But, to get you started, I've added comments to your code:
function check(){
var xx =document.getElementById("of");
var box = document.getElementsByName("chk");
// Loop over all the checkboxes
for(var i=0 ; i<box.length;i++){
// If the box is checked....
if(box[i].checked == true){
x=x+1; // Increase a counter
}
// If the counter is equal to the amount of checkboxes....
if (x == box.length){
xx.checked = true; // Make the "of" checkbox checked
}
}
}
Variable x is not defined. Does this help?
function check() {
const checkBoxes = document.getElementsByName("chk");
const toBeChecked = document.getElementById("of");
//initialize a counter
let counter = 0;
//loop over all checkBoxes
for (let i = 0; i < checkBoxes.length; i++) {
//check if current checkBox is checked and increment counter
if (checkBoxes[i].checked) {
counter++;
}
}
//check if all checkBoxes are checked and if so set the other checkBox to set
if (counter === checkBoxes.length) {
toBeChecked.checked = true;
}
}

JavaScript table for loop wrong checkbox value

I'm for looping data in my page, and they are showing fine, but when I'm trying to click one of three checkboxes and hide desired rows, it seems that get the wrong value.
This is the link of the live page in action.
This is the code that needs to be fixed.
https://musing-jang-0e572c.netlify.com/senate-data.html -> PAGE
https://github.com/Makkoyev/ubiqum-task2/blob/master/assets/js/manipulation.js -> Checkboxes section GitHub
This is the code:
(function () {
if (currentURL.indexOf("senate-data.html") == true) {
getSenate();
cbs = document.querySelectorAll("input[type=checkbox]");
targets = document.querySelectorAll("#table tr td:nth-child(2)");
tr = document.querySelectorAll("#table tr");
for (i = 0; i < cbs.length; i++) {
cbs[i].addEventListener('change', function () {
if (this.checked) {
// Checkbox is checked..
console.log("Checkbox checked!", this.value);
for(i = 0; i < targets.length; i++){
if(this.value == targets[i].innerHTML){
console.log("Uguale", targets[i]);
targets[i].parentNode.classList.add("hide-row");
}
}
} else {
// Checkbox is not checked..
console.log("Checkbox unchecked!", this.value)
}
});
}
}
if (currentURL.indexOf("house-data.html") == true) {
getHouse();
}
})();
You likely want something like this
FIDDLE
window.addEventListener("load", function() { // on page load
[...document.querySelectorAll("input[type=checkbox]")].forEach(function(cbs) { // take all checkboxes
cbs.addEventListener('change', function() { // when they change
var vals = [...document.querySelectorAll(".filters input[type=checkbox]:checked")].map(chk => chk.value); // get all checked values
[...document.querySelectorAll("#table tr td:nth-child(2)")].forEach(function(target) { // for all cell 2
target.parentNode.classList.toggle("hide-row",
vals.indexOf(target.textContent) == -1); // hide the ones NOT in the above list
});
});
});
})

How to delete 2 rows at a time using JavaScript

How to delete two rows at a time using JavaScript even though only for first row radio button exist?
Something like this:
1st row: (radiobutton) some textfield
2nd row: text field
On click of delete button, both the row should get deleted but the code which I have written is deleting only 1st row not 2nd one.
JavaScript code looks something like this:
function deleteReserveDetails() {
if (!document.forms[0].reserveRadiobutton) {
return;
} else {
var hidValue = parseInt(document.forms[0].Hd1Value.value);
var reserveRows = document.getElementById('reserveTable').getElementsByTagName('tr');
var headerNo = 1;
var radio = eval("document.forms[0].reserveRadiobutton");
if (radio.length == undefined) {
if (radio.checked) {
var hidValue1 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue1;
document.getElementById('reserveTable').deleteRow(headerNo);
}
return;
}
var k = 0;
for (var j = 0; j < radio.length; j++) {
if (radio[j].checked) {
if (j == hidValue - 1) {
var hidValue2 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue2;
}
document.getElementById('reserveTable').deleteRow(j + headerNo);
}
}
}
}
Could you please show me how to modify it to delete 2 rows at a time?

How can we count the number of check boxes checked inside a grid view in asp.net using javascript?

I asked this question in an interview. In asp.net how can we check the no. of checked boxes using javascript.
By using jquery you can get the number of checkboxes on a html page by this
alert($('input:checkbox').length);
Or by using the following jquery code to determine the complete picture
var totalNoOfChkBoxes = 0;
var NoOfCheckedchkBoxes = 0;
var NoOfUnCheckedChkBoxes = 0;
$('input:checkbox').each(function () {
if ($(this).is(':checkbox')) {
totalNoOfChkBoxes += 1;
if($(this).attr('value') == "on")
NoOfCheckedchkBoxes += 1;
else
NoOfUnCheckedChkBoxes += 1;
}
});
alert(totalNoOfChkBoxes);
alert(NoOfCheckedchkBoxes);
alert(NoOfUnCheckedChkBoxes);
alert($('input:checked[type=checkbox]').length);
This will display number of checked checkboxes in a page.
var inputs = document.getElementsByTagName("input");
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes

Making a row editable based on a checkbox in HTML

I have a table in HTML. The contents of this table are dynamically populated. Every row of the table has text boxes and one checkbox. When the page is loaded, all the text boxes in the rows will be in a read-only state.
Now, i want to change the state of the text boxes in a particular row to editable, if the check-box in that row is selected. Also, the text boxes should be made read-only if the check box is de-selected.
How could I accomplish this using Javascript? Please help me.
stating this with plain javascript would be pure pain :)
i suggest using jQuery, eg:
$(':checkbox').click(function() {
var checkbox = $(this);
var row = checkbox.closest('tr');
var inputText = $('input[type=text]', row);
if (checkbox.is(':checked')) {
inputText.attr('readonly', 'readonly');
}
else {
inputText.removeAttr('readonly');
}
});
otherwise
function HandleClickOnCheckbox() {
var checkbox = this;
var row;
var iter = checkbox;
while (!row) {
iter = iter.parent;
if (iter == window) {
break;
}
if (iter.tagName == 'tr') {
row = iter;
break;
}
}
if (!row) {
alert('row not found');
return false;
}
var textBoxes = GetTextBoxes(row);
var method;
if (checkbox.checked) {
var disabledAttribute = document.createAttribute('disabled');
disabledAttribute.nodeValue = 'disabled';
method = function(textBox) {
textBox.setAttributeNode(disabledAttribute);
};
}
else {
method = function(textBox) {
textBox.removeAttribute('disabled', 0);
}
}
for (var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
method(textBox);
}
}
function GetTextBoxes(element) {
var textBoxes = new Array();
for (var i = 0; i < element.children.lenght; i++) {
var child = element.children[i];
if (child.tagName == 'input') {
if (child.type == 'text') {
textBoxes.push(child);
}
}
if (child.tagName == 'td') {
var childTextBoxes = GetTextBoxes(child);
if (childTextBoxes.length) {
for (var j = 0; j < childTextBoxes.length; j++) {
var childTextBox = childTextBoxes[j];
textBoxes.push(childTextBox);
}
}
}
}
return textBoxes;
}
this is not tested!
Perhaps, you can start by handling the click event of the checkbox using an if/else statement to check if the checkbox is actually checked. If it is you can use the row within which the checkbox resides to find all the textboxes in the different cells and enable/disable them.
Are you using JQuery or plain Javascript?
If you don't mind using jQuery, you could do:
$('checkbox').click(function() {
if ($(this).attr('checked')) {
$(this).parents('tr').children('input[type="text"]').each().attr('readonly', 'readonly');
} else {
$(this).parents('tr').children('input[type="text"]').each().removeAttr('readonly');
}
})
Or something like that. I'd have to test it to be sure.
Edited to reflect Andreas's comment.
Try this snippet (assumes that the checkbox has a class called "checkbox") if you are using Jquery.
jQuery('tr.checkbox').click(function() {
if (jQuery(this).is(":checked")) {
jQuery('td', this).removeAttr('disabled');
} else {
jQuery('td', this).attr('disabled', '');
}
});`

Categories

Resources