Toggle checkboxes on PHP table - javascript

I have a table with a checkbox in the table header, which will be used to toggle all the checkboxes below it. I've add a JavaScript function to the checkbox in the header, but so far it only selects the top checkbox (one checkbox) instead of all of them. Any suggestions or advice on what I've done wrong or what to research?
HTML table header code:
<thead>
<tr>
<th><center><input type="checkbox" value="" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"></center></th>
<th>Sender</th>
<th>Receiver</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>
PHP table code:
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_1" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Javascript code:
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}

The problem is you setting the same ID (cb1_1) to all the checkboxes (which is invalid in HTML) Id should be unique in the page. Thus, it only select the first found checkbox and discard the rest. To resolve this give unique ids to checkboxes.
$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_'.$pmid.'" class="cbgroup1"></center></td>
<td>'.$sender.'</td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';
Note: I just use the $pmid just as an example you should use appropriate value as per your scenario

I see 2 issues with you code.
(Probably) using the same id for multiple DOM elements
Your PHP code suggests that you are probably using a loop to create the checkboxes but you are using the same id for all of them "cb1_1".
Same as #atul here.
Improperly selecting your checkbox elements
Since you are using the same id for all inputs,
var cb = document.getElementById(cbarray[i].id);always returns the same element. A way to solve it is to use the solution provided by #atul
Another way is to rewrite your javascript as follows :
function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = cbarray[i];
cb.checked = master.checked;
}
}
Your cbarray is already your checkboxes array, so it is redundant (aka useless) to call document.getElementById(cbarray[i].id) to get the element when you already have it with cbarray[i].

Related

How to loop through group of check boxes that have same class name?

I have dynamic table that has table cell with checkbox field. This fields are populated from DB so my table is dynamic. I would like to loop through checkboxes based on their class name. In that loop I want to check value for each check box. For example if value is equal 1 I want checkbox to be checked, if not unchecked. Alo I'm not sure if possible but I would like to set unique ID for each of these check boxes. Since my table is dynamic my fields need to have unique ID's. Here is example of my code:
<table>
<thead>
<tr>
<th>#</th>
<th>Time Slots</th>
<th>Block</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>~(SLOT_LABEL)</td>
<td>
<span>
<input type="checkbox" name="CF-[Events]" class="block" id="block_"+Value that will make this ID unique. value="~(SLOT_ID)"/>
</span>
</td>
</tr>
</tbody>
</table>
Also in current language that I work with to read values from DB I have to use NAME tag. If anyone can help please let me know. Thank you.
You can use the attribute selector to retrieve elements by both their name and value. Try this:
$('input[name="CF-[Events]"][value="1"]').prop("checked", true);
Working example
If you don't want a jQuery solution, it is also possible to fetch these elements with the querySelector:
var inputs = document.querySelectorAll("input.block");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
you can do it in jquery by each loop
$('.ClassName').each(function(i, o) {
// o is object in your case checkbox
// i is index
// your code
});
$("input[name='CF-[Events]']").each(function() {
if($(this).val() === "1")
{
$(this).prop("checked", true);
}
});

JavaScript is not working on Swedish letters

My javascript code for filtering is not working on Swedish letters å ä ö
<input name='tablefilter' type='checkbox' value='Linköping' id='tablefilter1' checked/>
<label for='tablefilter1'>Linköping</label>
<input name='tablefilter' type='checkbox' value='Mjölby' id='tablefilter2' checked/>
<label for='tablefilter2'>Mjölby</label>
<input name='tablefilter' type='checkbox' value='Norrköping' id='tablefilter3' checked/>
<label for='tablefilter3'>Norrköping</label>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody id='tablebody'>
<tr>
<td>Linköping</td>
<td>One</td>
<td>First</td>
</tr>
<tr>
<td>Mjölby</td>
<td>Two</td>
<td>Second</td>
</tr>
<tr>
<td>Norrköping</td>
<td>Three</td>
<td>Third</td>
</tr>
</tbody>
</table>
js
/* Demo filtering table using checkboxes. Filters against first td value */
/* Set 'ready' handler' */
document.addEventListener('DOMContentLoaded', initFunc);
/* When document ready, set click handlers for the filter boxes */
function initFunc(event) {
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
filters[i].addEventListener('click', buildAndExecFilter);
}
}
/*
This function gets called when clicking on table filter checkboxes.
It builds a list of selected values and then filters the table based on that
*/
function buildAndExecFilter() {
var show = [];
var filters = document.getElementsByName('tablefilter');
for (var i = 0; i < filters.length; i++) {
if (filters[i].checked) {
show.push(filters[i].value);
}
}
execFilter(show); // Filter based on selected values
}
function execFilter(show) {
/* For all rows of table, see if td 0 contains a selected value to filter */
var rows = document.getElementById('tablebody').getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var display = ""; // Default to display
// If it is not found in the selected filter values, don't show it
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
// Update the display accordingly
rows[i].style.display = display;
}
}
http://jsfiddle.net/2Lm7pytt/4/
It works on jsfiddle, but it's not working on my visual studio. The problem is not that it can't display Swedish letters, because it can.
The problem is that the JavaScript is not working on Swedish letters.
What should I do to make it work?
you might try adding to the top of the head tag
< meta charset="utf-8" />
This could fail at several points but it is most likely failing on the comparison due to an encoding issue, so I would suggest using the debugger to breakpoint the JavaScript before this line:
if (show.indexOf(rows[i].children[0].textContent) === -1) {
display = "none";
}
Check what is contained within textContent, try doing a comparison in your Immediate Window, e.g. rows[i].children[0].textContent === "Linköping". If you find this coming back false, this will likely confirm it.
Go to FILE > Advanced Save Options in Visual Studio and check the encoding option set here - I am using "Unicode (UTF-8 with signature) - Codepage 65001" and my code includes the meta code as seen in Brandon's suggestion in the answers below. With these set, it is running as intended, for me.

Checking variable for multiple inputs after onChange event

So I have a dynamic form that has two columns. One has a job name and the other has an input box where the user could enter their on description of the job.
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name" name="job_name"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" name="job_desc" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,)" />
</td>
</tr>
';
}
So as you can see I have a while loop that populates this form. So it could potentially have a lot of input boxes that you can use to describe the jobs.
The issue I am having is that, when I handle this form with the AJAX I have set up. The javascript simply grabs the last job on the list and uses that as it's jobs name. So in essence it is grabbing the input box correctly it's just placing it in the wrong row.
Here is the javascript that handles this change.
var job = document.getElementsByNames("job_name").value;
var comment = document.getElementsByNames("job_desc").value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php
echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
I know I should be grabbing the elements with getElementByNames but I just don't know how to pair up the comment with the proper job that it's supposed to go with. So if someone comments next to the input box for Granite Job the comment should be paired up with the job name 'Granite Job' in the database. Instead currently it will just be paired up with the last job on the list which is 'Cabinet Assembly'.
Any help would be appreciated.
First of all, you have a HTML error for the attribute id
You may not in HTML standards to give a same value for id attribute to a multiple elements.
But fortunately we can use this unique identifier to make your code works
You can edit your PHP code to some thing like this:
$counter=0;
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name_'.$counter.'"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" id="job_desc_'.$counter.'" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,'.$counter.')" />
</td>
</tr>
';
$counter++;
}
You can see we added a counter to identify our rows
Updating your Javascript code will be as follow:
var insertCommentInstall=function(value,identifier){
var job = document.getElementById("job_name_"+identifier).value;
var comment = document.getElementById("job_desc_"+identifier).value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
}
When you use a selector like getElementsByClassName or getElementsByTagName you are retrieving a nodelist of all elements with the specified attribute (adding a classname to your inputs would make this easier). You need to specify one particular node out of the nodelist in order to fetch it's value. In order to retrieve all values in your nodelist you need to loop through it and push the values of all its nodes into an array.
//finds all elements with classname "jobs"
var jobs = document.getElementsByClassName("jobs");
//create new array that we push all the values into
var jobValues = [];
//loop through our jobs nodelist and get the value of each input
for (var i = 0; i < jobs.length - 1; i++) {
jobValues.push(jobs[i].value);
}
jobValues; //gives you a list of all the values you pushed into the array
jobValues[5]; //gives you the value of the 6th input you looped through

Getting All HTML Checkboxes (Array) Checked with Javascript (and PHP)

I've been searching for this for a couple hours with no luck. This seems like it should be fairly easy but I am obviously overlooking something.
I have a table, with each row displaying information in each cell. At the end of each of the rows, there is an additional cell with a checkbox in it. The checkbox is an array, and each checkbox value is an imploded array via PHP. See below:
HTML/PHP
--------
(...some html code...)
<form method="post" action="the-next-page.php">
<table>
<tr>
<?php
(...some php SQL query code...)
while ($row = oci_fetch_array($result)) {
?>
<td><input type="text">Name</td>
<td><input type="text">City</td>
<td><input type="checkbox" name="checkGroup[]" value="<?php implode(":",$someArrayvariable) ?>"></td>
<?php
}
?>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
....
</html>
Passing the imploded values to the next page works fine. No problem there.
I have been trying to create a javascript function to check all of the boxes that are in this form, or under the checkbox group's name, or whatever I can do to check them all with the click of a button. I've tried variations of the following with no success:
HTML (On the top of the same script as above)
----
<button name="checkAll" onclick="checkAll()">Check All</button>
Javascript (On the bottom of the same script as above)
----
<script type="text/javascript">
function checkAll() {
var checks = document.getElementByName("checkGroup");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
</script>
I can't figure out what I'm doing wrong. I know that a variation of this question has been asked before many times, but I don't seem to be getting any results. I'm guessing because my checkboxes name is an array (checkGroup[] ???).
When I click the button to check all of the checkboxes in the form, nothing happens.
Any ideas? Thanks in advance.
-Anthony
You can use JQuery to make this easier on yourself.
I would also assign a general class name to each checkbox input, so then in Javascript (using JQuery):
$(".classname").each(function() {
$(this).prop("checked",true);
});
I would also give the Check All button a unique class/id so you can do this
$(document).ready(function() {
$("#allcheckboxid").on("click",function() {
$(".classname").each(function() {
$(this).prop("checked",true);
});
});
})
Two minor things:
function checkAll() {
var checks = document.getElementsByName("checkGroup[]");
for (var i=0; i < checks.length; i++) {
checks[i].checked = true;
}
}
getElementByName should be getElementsByName, and checkGroup should be checkGroup[]. Other than that your code should be good to go!
Try this way to get all checked check box elements
<button name="checkAll" onclick="checkAll()">Check All</button>
<script type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('checkGroup[]');
var checkboxesChecked = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
</script>

editing dynamically generated table

I have a dynamically generated tables the foot of the table contain some text fields when click on save i want to add the value of text fields to the body of that table .
here is the table
<table border="1" class="entity_table">
<tfoot>
<tr>
<td>
<div class="pane1"></div>
<div class="pane2">
<input type="text" id="name"><br>
<select id="data">
<option value="1">int</option>
<option value="2">tinyint</option>
</select>
<br><span id="save">save</span>
</div>
</td>
</tr>
</tfoot>
<tbody class="table-body" id='myid'></tbody>
</table>
i did this but this is id specific ..i want to update that specific table on which it is clicked and edited .
var myName = document.getElementById("name");
var data = document.getElementById("data");
var Mtable = document.getElementById("myid");
var rowCount = Mtable.rows.length;
var mrow = Mtable.insertRow(rowCount);
var mcell = mrow.insertCell(0);
mcell.innerHTML = myName.value;
var mcell1 = mrow.insertCell(1);
mcell1.innerHTML = size.value;
i want to update each dynamically generated table with values that is entered in its table's foot section
You can use below jQuery :
$(function(){
$('#save').click(function(){
$(this).closest('table').find('tbody').append('<tr><td>'+$('#name').val()+' and '+$('#data').val()+'</td></tr>');
});
});
Demo
EDIT - to eliminate input and select box id dependency use below code :
$(function(){
$('#save').click(function(){
var name = $(this).closest('tr').find('input[type=text]').val();
var data = $(this).closest('tr').find('select').val();
$(this).closest('table').find('tbody').append('<tr><td>'+name+' and '+data+'</td></tr>');
});
});
Demo
So if I understood this right, you dont want to use element's ID to select it.
You have some else options if you dont want to work with elements IDs:
1) You can add them some data- attribute, for example: data-id. And based on this you select your element like this:
myElement.querySelector("[data-id='X']") where myElement is some parent element of your tables and X is their ID which you generated before (lets say it will start from 0 and will increment with every next table).
2) If possible, work with objects. When you create your tables, you either create them with raw text with defining html elements or you create new elements with calling createElement("table") on document keyword. If second option is your option, you can save this elements to some array (myTables in this case) and then approach this elements in a standard way - lets say:
myTables[0].getElementsByTagName("input")
Hope it helps your issue. Hope I understood issue you were asking about.

Categories