Checkbox using Javascript - javascript

I have created a table which has a checkbox to select, and pagination is also there for the table. My problem is that if I select two boxes from first page and select few more in the second, only the boxes which i selected in the last page are getting displayed and the others are not coming. Please answer me if u are aware.
Here is my code :
function getSelectedEquipmentIds() {
var equipmentIds = "";
var checkboxs = document.getElementsByName("instance");
for ( var i = 0; i < checkboxs.length; i++) {
if (checkboxs[i].checked) {
equipmentIds += checkboxs[i].value + ";";
}
}
return equipmentIds;
}

Related

How to get checked rows' values from html table on a sidebar using GAS?

I have a table whose rows consist of 3 columns. 1º is a checkbox, 2º contains the colors and the 3º contains the hex.
As the user selects the colors desired by ticking the checkboxes, i imagine the colors being pushed into an arrat, that will be written to a cell as the user clicks on the save button.
I've borrowed this snippet from Mark, but it doesn't seem to run in my context:
var checkboxes = document.getElementsByTagName("input");
var selectedRows = [];
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
selectedRows.push(secondColumn);
};
console.log(selectedRows)
}
This is the javascript part running to load and populate the table and I'm not sure where the above snippet woud go into:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
/**
* Run initializations on sidebar load.
*/
$(function() {
// Assign handler functions to sidebar elements here, if needed.
// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run
.withSuccessHandler(function (record) { //<-- with this
showRecord(record);
})
.withFailureHandler(
function(msg, element) {
showStatus(msg, $('#button-bar'));
element.disabled = false;
})
.getRecord();
});
/**
* Callback function to display a "record", or row of the spreadsheet.
*
* #param {object[]} Array of field headings & cell values
*/
function showRecord(record) {
if (record.length) {
for (var i = 0; i < record.length-1; i++) {
// Adds a header to the table
if(i==0){
$('#sidebar-record-block').append($($.parseHTML('<div class="div-table-row"><div class="div-table-header">Sel</div><div class="div-table-header">Color</div><div class="div-table-header">Hex</div></div>')));
}
// build field name on the fly, formatted field-1234
var str = '' + i;
var fieldId = 'field-' + ('0000' + str).substring(str.length)
// If this field # doesn't already exist on the page, create it
if (!$('#'+fieldId).length) {
var newField = $($.parseHTML('<div id="'+fieldId+'"></div>'));
$('#sidebar-record-block').append(newField);
}
// Replace content of the field div with new record
$('#'+fieldId).replaceWith('<div id="'+fieldId+'" class="div-table-row"></div>');
$('#'+fieldId).append('<input type="checkbox" class="div-table-td" id=CB"'+fieldId+'"name="checkBox" </input>')
.append($('<div class="div-table-td">' + record[i].heading + '</div>'))
.append('<div class="div-table-td">' + record[i].cellval + '</div>')
}
}
}
</script>
Sample of how to get the checked tickboxes an button click
Assuming all your checkboxes are tied to a row, you can loop through all checkboxes with a query selector,
access their checked status
and save the indices of those checkboxes.
Those indices will be the same as when looping through the corresponding table rows.
Sample implementing a button click event:
var saveButton = document.getElementById("myButtonId");
saveButton.onclick = function(){
var checkedRowIndices = [];
$('input[type=checkbox]').each(function( index ) {
if($(this)[0].checked{
checkedRowIndices.push(index);
}
});
};
//now get the rows with those indeices and do something with them

how to get previously selected rows of a bootstrap dataTable while searching

I have used a bootstrap DataTable to show data. At the same time i have a HTML checkbox as a column of that dataTable. I have a submit button to get the selected checkbox's value to do some stuff. I am fetching the following problem while select checkboxes under searching.
When i select all checkboxes and Click Save button I got all the values. It works as my expectation.
But Unexpected occures when i search via built-in search box of bootstrap dataTable.Here is the pictorial view
In this case when i press Save i got just the two value though all other values are still selected. How can i get all the selected values while searching
Here is my jquery code of Save button of getting the checkboxes value
$("#btnSave").click(function () {
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
....
//Other stuff
....
}
Please help me.
When you are doing a search, it is going to check only for the rows, that satisfy the given criteria. So your search logic works like this
if(searchCriteria==true)
{
showValue
}
Even if you had previously selected values it won't be showing all of them, because they don't satisfy the given criteria. Now in this case when you click on Save, it is taking only those rows in the datatable which are checked and satisfy the given criteria, as per your java script.
Now if you still wish, that all selected values should be taken in, there is one way you can try, put the selected values in some kind of List or Set, and place the list object in session. So everytime you click on Save, you can retrieve the List from the session. But I really don't see why you would want to do it, unless you need to retrieve the selected values every time.
I got my job done like this
var table = $('#tblReportList').dataTable();
When i was searching through dataTable, i was getting just the selected values matching the search criteria. But the previously selected values was disappeared. To get the previously selected value i used the following code...
table.$('input[type="checkbox"]').each(function () {
if (!$.contains(document, this)) {
if (this.checked) {
previousVal = previousVal + ',' + this.value;
}
}
});
Now, for getting the selected values of search I used the previous code posted before. And that was
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
So all selected checkbox's values are
var allValues=previousVal+vals;

javascript prop( checked, true) not working

I have a list of checkbox, on many pages, when I move from one page to other I need to check if any checkbox is in temporary table, if it is to mark it like checked.
$(document).on('click','.page a',function (){
for (i = 0; i < 20; i++) {
var p = $(this).attr('data-page');
//console.log(p);
x = i + 20 * p;
if (keys.indexOf(x) > -1) {
$(':input[value="'+x+'"]').prop('checked',true);
console.log(x);
}
};
});
After I click on next page (where I clicked before on checkbox) I see checked checkbox_id( in this line console.log(x); ) but they are not checked when I get to the page. The result look like this.
For display I use yii2 gridview between tags Pjax.

Check appropriate checkboxes when certain option is selected from dropdown select?

fiddle
I'm sorry to ask this question, I hate asking on here and I don't wanna be seen as a vampire but I'm so stuck with this and I don't think I'm on the right lines at all, if this doesn't make sense at all comment and I'll try explain. I'm desperate!
Basically what I'm working on requires you to select a company, and when you do that it generates some checkboxes. When you select a profile from the dropdown, it needs to tick the appropriate checkboxes. The checkboxes it should tick are whatever that profile has in it's PRIVILEGE_PROFILES.PRIVILEGE CODES (these are the checkboxes).
I've got my code in a fiddle here http://jsfiddle.net/shaunyweasel/dj8jr19e/5/ . The arrays are at the top of the fiddle. I was trying to do it so that if the text value of the label was equivalent to to the SEC_PRIVILEGES.Name then tick those checkboxes, however that doesn't really work so I'm not sure if there's a better way to go about it. The below method is what I've been working on to try get it to tick the checkboxes but I'm pretty sure it's wrong.
$(document).on('change', '#select_profile', function () {
var select = $("#select_profile option:selected").text(),
selectedProfile, privileges, div, label, access;
var checked = document.getElementsByTagName('input');
for (var i = 0; i < checked.length; i++) {
if (checked[i].type == 'checkbox') {
checked[i].checked = false;
}
}
if (select !== 'None') {
for (var i = 0; i < PRIVILEGE_PROFILES.length; i++) {
if (PRIVILEGE_PROFILES[i].PROFILE_ID === select) {
selectedProfile = PRIVILEGE_PROFILES[i];
privileges = selectedProfile.PRIVILEGE_CODE;
}
}
for (var i = 0; i < SEC_Privileges.length; i++) {
if (privileges[i] === SEC_Privileges[i].Unique_Code) {
console.log(privileges);
var labels = document.getElementsByTagName('label');
var checked = document.getElementsByTagName('input');
for (var c = 0; c < checked.length; c++) {
if (SEC_Privileges[i].Name == labels) {
checked[c].checked = true;
}
}
}
}
}
});
If this doesn't make sense, here's a step by step of how it works and where i'm at and stuck:
User selects a company from the company_selection dropdown
When company is selected it generates checkboxes for that company depending on it's COMPANY_PRIVILEGES.UNIQUE_CODE (the array)
The user then has to select something from the profile_selection, and depending what profile they select it will check the appropriate checkboxes, depending on what PRIVILEGE_PROFILES.PRIVILEGE_CODES it has. (so if you selected Crew then it would just tick the View Tyrell box as that's the only profile it has)
Is there a reason why you do not use jQuery selectors in your code?
Anyway, I've made an update to solve your problem (not using jQuery) http://jsfiddle.net/dj8jr19e/7/
The main issue is that you did not set any IDs to your checkboxes.
I've set an ID corresponding to the Unique_Code of your privileges.
access.id = SEC_Privileges[i].Unique_Code;
Then when you iterate through the associated privileges from the selected profile, I've simply used getElementById because the privileges contains Unique_Code used as Ids of the checkboxes.
Here is the working example: DEMO
I have changed following things:
1) When you are creating the checkboxes then i have added class name to those checkboxes similar to UNIQUE_CODE
$(document).on('change', '#select_company', function () {
// declare variables before the function
var select = $("#select_company option:selected").text(),
selectedProfile, privileges, div, label, access;
// remove access checkboxes from previously selected profile
$('.apps input[type=checkbox]').remove();
$('.apps label').remove();
// if the selected option is 'None', do nothing, else...
if (select !== 'None') {
// match the selected profile in the dropdown with the JS PROFILES object
for (var i = 0; i < COMPANY_PRIVILEGES.length; i++) {
if (COMPANY_PRIVILEGES[i].COMPANY_CODE === select) {
selectedProfile = COMPANY_PRIVILEGES[i];
privileges = selectedProfile.UNIQUE_CODE;
}
}
// match the associated privileges from the profile within the entire privilege list
for (var j = 0; j < privileges.length; j++) {
for (var i = 0; i < SEC_Privileges.length; i++) {
if (privileges[j] === SEC_Privileges[i].Unique_Code) {
// get the div with the id === SEC_Privileges[i].Group_code
div = document.getElementById(SEC_Privileges[i].Group_Code);
access = document.createElement('input');
access.type = 'checkbox';
access.className = SEC_Privileges[i].Unique_Code;
label = document.createElement('label');
// create a textnode with the unique code from the privileges
label.appendChild(document.createTextNode(SEC_Privileges[i].Name));
div.appendChild(label);
div.appendChild(access);
}
}
}
}
});
2) Written simple function to check the checkbox based on the classname:
$(document).on('change', '#select_profile', function () {
var selectedValue = $("#select_profile option:selected").text(),
selectedProfile, privileges, div, label, access;
console.log(selectedValue);
for (var i = 0; i < PRIVILEGE_PROFILES.length; i++) {
if (PRIVILEGE_PROFILES[i].PROFILE_ID === selectedValue) {
privileges = PRIVILEGE_PROFILES[i].PRIVILEGE_CODE;
}
}
for(var j = 0; j < privileges.length; j++) {
$('.'+privileges[j]).attr("checked", "true");
}
});

How do you count checked checkboxes, excluding the header, in an asp.net gridview using javascript?

I'm currently counting all the checked checkboxes in an asp.net gridview using:
$('#cphMain_gdvSalesOrder').delegate('input:checkbox', 'click', function() {
var count = $('#cphMain_gdvSalesOrder').find('input:checkbox:checked').length;
Whereas I need to count all the checkboxes that are checked apart from the one in the header.
Any ideas would be great, thanks
Korv
You can assign a "flag" CSS Class to the check-boxes in the grid which is not assigned to the check-box in the header. This way you can filter out the header check-box as part of your selector based on CSS Class.
:not(.headerCheckBox)
var count = 0;
var grid = document.getElementById("<%=grdProductImage.ClientID%>");
var chk = grid.getElementsByTagName("input");
for (var i = 0; i < chk.length; i++)
{
if (chk[i].checked && chk[i].id.indexOf("chkAll") == -1) {
count = count + 1;
}
}

Categories

Resources