Javascript: how to get values from all selected checkboxes from a table - javascript

I've searched in many threads but i don't see any checkboxes that involves tables, i just wanted to make deleting easy for users, Say, i have a table with fifty entries and i wanted to delete 10 all in one go, so i select the check box beside each record so when i want to delete it it will just get the values of the checkbox pass it on to a php script..
My question is how do i im[plement this on Javascript or jQuery?. getting the values from n numbers of checkboxes? since tables have a dynamic value depending on how many it has on the database.
Here is an image to be clear:

This will give you an array containing the value attribute of each checked box:
var values = $('input:checked').map(function() {
return this.value;
}).get();
See http://jsfiddle.net/p58Hw/1/

Select your table, find all rows with a checked checkbox, store their values, and remove them:
var $chkboxes = $(yourTable).find("tr input[type='checkbox']:checked");
var checkBoxVals = $chkboxes.map(function(){ return $(this).val(); }).toArray();
$chkboxes.closest('tr').remove();
// serialize array checkBoxVals and pass it to your php script

You would post your code. But try something like this:
$('.YourCheckboxClass:checked').each(function() {
// your code here
});

Related

Tabulator.js: get/select rows on current page

I am using an amazing tabulator plugin for managing tabular data, API is very clear and reliable but i cant do a very simple thing: get/select all rows on current page.
Custom row selection can look like this:
table.selectRow(table.getRows().filter(row => <<Custom Selection>>);
Where Custom selection has to respect the current page, but i dont get from where i can take it.
Maybe i am missing something?
There is no way to do that directly form Tabulator, but is should be fairly easy to do yourself with a bit of JavaScript.
First you want to get the rows that are visible on that page:
var pageRows = table.getRows(true);
Then you want to get the selected rows
var selectedRows = table.getSelectedRows();
then you want to find rows that exist in both arrays, these will be the selected rows on that page:
var rows = selectedRows.filter(value => -1 !== pageRows.indexOf(value));
Assuming the column name of your index is 'id' you can do the following:
var selectedData = table.getSelectedData();
jQuery.map(selectedData, function(value, index) {
console.log(value.id);
});

How to get checkbox value from localStorage

There is a page with a lot of different checkbox questions which then get submitted and populate the next page, this page however gets refreshed and the already annoyed potential client needs to go back and fill out the form again.
Now I have localstorage set up so he doesn't need to reselect all the checkbox again, he just needs to resubmit the form and his back in action.
How does one keep the values populated on the problem page so this fella doesn't have to go back to resubmit?
//SIZE SAVE
function save() {
localStorage.setItem('100', checkbox.checked);
var checkbox = document.getElementById('100');
localStorage.setItem('200', checkbox.checked);
var checkbox = document.getElementById('200');
//SIZE LOAD
function load() {
var checked = JSON.parse(localStorage.getItem('100'));
document.getElementById("100").checked = checked;
var checked = JSON.parse(localStorage.getItem('200'));
document.getElementById("200").checked = checked;
//THIS PAGE NEEDS THE CHECKMARK
echo get_site_url().
"/the/checkmark/selected/was/".$_POST['check_group'].
"/.png";
}
I think is much simple for now and especially for the feature if you write some code to make the management for all checkboxes form your form.
First of all it will be best if you group all your checkboxes into a single place.
Into a function like this you can declare all your checkbox selectors you want to save into the localStoarge (now you don't need to make variables for each selector into multiple places into your code)
function getCheckboxItems() {
return ['100', '200']
.map(function(selector) {
return {
selector: selector,
element: document.getElementById(selector)
}`enter code here`
});
}
Then to make things much simpler you can store all the values from the checkbox into a single object instead of save the result in multiple keys, in this way is much simpler to make management (let's say you want to erase all values or to update only a part)
The following function will take as argument all checkbox items from the function above, the point is the function above will return an array with the checkbox id and the checkbox element, than you just reduce all that array into this function into an single object containing all the ids and values, after this you just store the object into the localStorage
function serializeCheckboxes(elements) {
var container = elements.reduce(function (accumulator, item) {
accumulator[item.selector] = item.element.checked;
return accumulator;
}, {})
localStorage.setItem('container', JSON.stringify(container));
}
function save() {
var elements = getCheckboxItems();
serializeCheckboxes(elements);
}
After this you need another function who will read all the values from the localStorge and place them into your checkbox "checked" state
function readCheckboxes() {
var storage = localStorage.getItem('container'), //Your key
container = (storage) ? JSON.parse(storage) : {};
Object.keys(container).forEach(function(key) {
var element = document.getElementById(key);
if(element) {
element.checked = container[key];
}
});
}
This is just a simple service who can manage your problem but I think, for any additional changes you can customize this solution much simpler instead of keeping all into multiple variables, also if you add more checkbox elements into your application with this solution you just add the corresponding id into the array from the first function.
A live example here:
https://jsbin.com/xejibihiso/edit?html,js,output
localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do
localStorage.setItem("checkbox_value", true)
and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so:
$(checkbox).is(':checked')
and use a simple if-else clause to pass in true or false. then when you reload your page, on $(document).ready() you can get the values using
localStorage.getItem(key)
and use JavaScript to set the check boxes values.
localStorage only allows you to store strings. What you can do is use a loop to create a string that has all the check boxes values separated by some delimiter. So, for example, if there are four check boxes with values true false false true your string would be "true\nfalse\nfalse\ntrue" where \n is the delimiter. then you can store that string in localStorage and when you retrieve it you can put all the values into an array like so:
array = localStorage.getItem(key).split('\n').
Then you can populate your check boxes with that newly retrieved array. Ask if anything needs clarification.

Change the div's in another html page

still learning some javascript here, got done other things but now the final and most important part of it.
I have two html pages - one of which uses javascript to dynamically add text-fields (and to remove them of course) (genmain.html) and the other one where the text field input should go(table.html).
So i have already created a function to retrieve the array of values.
function getElementArray(divName){
var names = document.getElementsByName("namefield");
}
The variable names is an array and it has all the values from fields.
The problem is I would like to set these values from array to the values of another div on the page. After some searching i understood that it could be done with 'id'-s but i'm not that sure and don't completely understand how.
Let's say i have a lot of div's on another page (table.html) but some of them have id="MAIN". I would like to change the value inside of the div
For example
<div id="MAIN">THIS PART I WANT TO CHANGE</div>
Javascript is not part of my school system and i've done CodeAcademy tutorials and that's the most i've got about this, I hope you guys can help with my issue.
The variable names is an array and it has all the values from fields.
function getElementArray(divName){
var names = document.getElementsByName("namefield");
}
Nope, you've only got reference to the elements here. You've not got the value yet.
You can get the values by iterating through the names Nodelist array and use names[i].value
The problem is I would like to set these values from array to the
values of another div on the page
If it's going to be in same page, then use innerHTML or textContent property of the DOM to assign the value.
document.getElementById("MAIN").textContent= names[1].value;
Just for demo purpose am using names[1] here so it will load the second input value.
Let's say i have a lot of div's on another page (table.html) but some
of them have id="MAIN". I would like to change the value inside of the
div
Once you move to another page, the javascript state will be lost. So you wont have access to names inside that page.
Either you must store the values into localStorage and retrieve in next page.
Else add the values to query string of your URL and retrive it there.
Edit: Update based on comments
Let us assume you have var names = document.getElementsByName("namefield"); so to store the values inside localStorage.
var myValues = [],
names = document.getElementsByName("namefield");
for(var i = 0; i < names.length; i++) {
myValues.push(names[i].value);
}
localStorage.myValues = JSON.stringify(myValues);
Now if your next page, Iinside window.onload event:
window.onload = function() {
var myValues = localStorage.getItem("myValues") ? JSON.parse(localStorage.getItem("myValues")) : [],
divElements = document.querySelectorAll("#MAIN");
for(var i =0; i < myValues.length; i++) {
divElements[i].textContent = myValues[i];
}
}
If you want to set or change the contents of an element, you can use the innerHTML property.
So in your case, document.getElementById("MAIN").innerHTML = "Whatever you want";
For the record, names in your example technically isn't an array, but a NodeList. See https://developer.mozilla.org/en/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F.

using jquery find on result set of find

When I do a find look-up on my table for hidden fields, I am seeing my two hidden fields. However, I want to further refine these 2 fields by their IDs. I notice that when I use find on the entire table using the "contains" that I get my 2 fields. However, if I do a find on the find results from the hidden fields, it returns an empty set. Can anyone explain why this is the case?
var table = sender.parentNode.parentNode.parentNode.parentNode;
// this finds my 2 hidden fields
var hidden_fields = $(table).find("input[type='hidden']");
// this finds each of the 2 fields individually by ID
var my_id_fieldA = $(table).find("[id*='hfMyIdFieldA']");
var my_id_fieldB = $(table).find("[id*='hfMyIdFieldB']");
// but this returns an empty set
var my_id_fieldA = $(hidden_fields).find("[id*='hfMyIdFieldA']");
You're looking for the filter function, not find. find selects child elements while filter filters the current selection.
Also there's no reason to find the table like that... try something like this.
var $table = $(sender).closest("table")
, $hidden_fields = $table.find("input[type='hidden']")
, $my_id_fieldA = $hidden_fields.filter("[id*='hfMyIdFieldA']")
, $my_id_fieldB = $hidden_fields.filter("[id*='hfMyIdFieldB']")
, $my_id_fieldA = $hidden_fields.filter("[id*='hfMyIdFieldA']")
;

A jquery combine multiple .html set attributes

I got some values gathered by ajax in this data like
$("#datset_egn").html(data['egn']);
$("#datset_tabnomer").html(data['tab_nomer']);
$("#datset_vhnomer").html(data['vh_nomer']);
$("#datset_podelenie").html(data['podelenie']);
$("#datset_email").html(data['email']);
etc. there are around 30 more and they are set together. Is there more elegant (easier and shorter) way to do this because I have to set the same amount of ids once again to blank if the ajax returns error ? Something like .. again:
$("#datset_egn").html('');
$("#datset_tabnomer").html('');
$("#datset_vhnomer").html('');
$("#datset_podelenie").html('');
$("#datset_email").html('');
To set them all, you can use the keys as they match the ID's
$.each(data, function(key, value) {
$('#datset_' + key.replace('_','')).html(value);
});
To reset them all, you can use the attributes starts with selector to select all elements where the ID starts with datset_
$('[id^="datset_"]').empty():
You could write a for loop that iterates through data values and sets the appropriate id.
for(var key in data){
$('#dataset_'+key).html(data[key]);
}

Categories