How to get checkbox value from inside an HTML table using JS - javascript

I'm currently working on a simple website where I have a list of PC parts in a table. In this table I also have checkboxes which are meant to be checked if the parts are owned. At the bottom of a table is a button which will be pressed that is meant to check the status of the checkboxes and output the list of parts still needed and the approximate cost.
I'm having issues with accessing the checked state of the checkboxes through Javascript and keep getting undefined when I try to output the value in the console.
Site Table Image:
HTML Code:
<div class="beginnersguide">
<h1>What parts go into a gaming PC?</h1>
<table id="partsTable">
<tr>
<th onclick="sortTable(0)" id="partName">Part Name</th>
<th>Image</th>
<th>Description</th>
<th onclick="sortTable(3, 1)" id="averagePrice">Average Price ($CAD)</th>
<th>Already Owned?</th>
</tr>
<tr>
<td>Case</td>
<td><img src="../img/case.jpg"></td>
<td>The nicely designed box/container for all your PC parts. This is what you will first see when looking at your PC!</td>
<td>150</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Motherboard</td>
<td><img src="../img/motherboard.jpg"></td>
<td>The Motherboard is a large circuit board which acts as the central hub for all your internal PC components. It will connect all the parts inside together to run!</td>
<td>210</td>
<td><input type="checkbox"></td>
</tr>
<tr>
// Code continues on like this for the rest of the table and ends like this:
<tr>
<td>Input and Output Devices</td>
<td><img src="../img/iodevice.jpg"></td>
<td>This would cover items such as a mouse, keyboard and monitors. These are needed to interact with your PC.</td>
<td>250</td>
<td><input type="checkbox"></td>
</tr>
</table>
<input type="submit" name="check" value="Check List" onclick="checkList()">
JavaScript Code:
/* Function for Parts checklist */
function checkList(){
var table, rows = 0;
table = document.getElementById("partsTable");
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
x = rows[i].getElementsByTagName("TD")[4];
//console.log(x);
if (x.checked == true){
/* code to output what parts are necessary */
}
}
}

Related

Filter Textfield Jquery in Pagination

Hi I am new to html javascript, jquery any help will be really appreciated I managed to create a table that has filter input but my problem is when I type in search box and i its filtering but when I backspace until the textfield is empty it showing whole rows of the table my pagination didntwork because in my first load without searching yet in the input textfield table showing two rows and has numbers page next button only showing two rows per page but if i filter search and make my field empty it will not limit the rows it will show all rows like right now i have six rows it will shows six rows where I want it to be only two rows shows and when click next two rows again *link for pagination --> https://www.jqueryscript.net/table/Client-side-HTML-Table-Pagination-Plugin-with-jQuery-Paging.html *
HTML
<table id="myTable">
<thead>
<tr>
<th>Firstname</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>100</td>
</tr>
<tr>
<td>Mary</td>
<td>200</td>
</tr>
<tr>
<td>July</td>
<td>300</td>
</tr>
<tr>
<td>Juy</td>
<td>3000</td>
</tr>
<tr>
<td>uy</td>
<td>1000</td>
</tr>
<tr>
<td>buy</td>
<td>10700</td>
</tr>
</tbody>
</table>
Javascript
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
$('#myTable').paging({
limit: 2,
rowDisplayStyle: 'block',
activePage: 0,
rows: []
}); });

How to send selected table rows value to another page in javascript

I have 2 pages and 2 tables, in page 1(table 1) I want to send selected rows to page 2(table 2) where in table 2 I show the selected rows
This is the first table in page 1:
<table class="src-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Jill</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Eve</td>
</tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
Like image below
This is the second table in page 2:
<table class="target-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
</table>
Like image below
If you really need this. You can use localStorage.
localStorage not working in the sandbox. But you can use it your application as well.
run storeItems when you need to save selected to store (for example on element select)
run appendStoredToAnouther on window event window.onload on page with the target table
function storeItems() {
const selectedItems = document.querySelectorAll("#first-table .selected");
const selectedHtml = nodeListToString(selectedItems);
localStorage.add('selectedTableItems', selectedHtml);
}
function nodeListToString(nodeList) {
let string = '';
nodeList.forEach(function(node) {
string += node.outerHTML;
});
return string;
}
function appendStoredToAnouther() {
const itemsHtml = window.localStorage.get('selectedTableItems');
const targetTable = document.getElementById('target-table');
targetTable.innerHTML = itemsHtml + targetTable.innerHTML;
}
<table id="first-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>
<button type="button" onclick="storeItems()">Send to anouther</button>
<button type="button" onclick="appendStoredToAnouther()">Append stored to anouther</button>
<table id="target-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>
Below I demonstrated how some lines could be carried over from one table to another one on a following page. However, since both pages are probably hosted on the same server it is in most cases more practical to first collect some unique identifiers for the selected table records, transmit them to the next page and then get the actual table contents from the original data source again (in many cases a database table or view). This approach will also make your page safer against unauthorised injections.
In case that the tables are to be shown in two consecutive pages you can do the following:
// shortcut for utility function querySelectorAll():
const qsa=(s,o)=>[...(o||document)['querySelectorAll'](s)];
const log=qsa('#log')[0];
qsa('#submit')[0].addEventListener('click',function(){
var dat="tbl="+JSON.stringify(
qsa('tr',qsa('.src-table')[0]).filter(tr=>qsa('input:checked',tr).length)
.map(tr=>qsa('td',tr).slice(1)
.map(td=>td.innerHTML))
);
log.innerHTML+="<hr>dat:"+dat;
log.innerHTML+="\nwindow.location=\"page2.html?\"+encodeURIComponent(dat)";
// this second part would be placed in the onload section if the next page:
log.innerHTML+='var dat=window.location.search.substr(1)'
var args=dat.split("&").reduce((a,v)=>{
var t=v.split('=');
a[t[0]]=JSON.parse(decodeURIComponent(t[1]));
return a;},
{}
);
qsa('.trg-table')[0].innerHTML+=
args.tbl.map((r,i)=>'<tr><td>'+(i+1)+'</td><td>'+r.join('</td><td>')+'</td></tr>').join('');
})
<h2>page one</h2>
<table class="src-table">
<tr><th>Select</th><th>Firstname</th><th>Familyname</th></tr>
<tr><td><input type="checkbox"></td><td>Jill</td><td>Jones</td></tr>
<tr><td><input type="checkbox"></td><td>Eve</td><td>Adams</td></tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
<h2>this would be the second page</h2>
<table class="trg-table">
<tr><th>no</th><th>Firstname</th><th>Familyname</th></tr>
</table>
<pre id="log"></pre>
As this is a sandbox the last lines had to modified a bit. In your page you should actually redirect your page with the window.location assignment.
On the second page you then need to read the passed information from window.location.search and use that information to append it to your table there.

How to get multiple selected cell array values with checkbox in jquery, then send with ajax post

How should I get an array value from a table cell when clicking checkbox with jQuery? If I've selected cell 1, I want to get array like ["BlackBerry Bold", "2/5", "UK"], but if I've selected all of them, I want to get all the data in the form of an array of arrays.
<table border="1">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
Please help.
Onclick get 3 children of the parent and add content to data. Used jquery nextAll for siblings and splice the 3 required.
Attached event to the table, onclick will check if element is INPUT.
If it's input, will get parent of that input which will be <td>.
For this parent element, will get three siblings using jquery.
Will add in selected if not present else delete, using indexOf.
CodePen for you to playaround: [ https://codepen.io/vivekamin/pen/oQMeXV ]
let selectedData = []
let para = document.getElementById("selectedData");
let tableElem = document.getElementById("table");
tableElem.addEventListener("click", function(e) {
if(e.target.tagName === 'INPUT' ){
let parent = e.target.parentNode;
let data = [];
$(parent).nextAll().map(function(index, node){
data.push(node.textContent);
})
let index = selectedData.indexOf(JSON.stringify(data))
if(index == -1){
selectedData.push(JSON.stringify(data));
}
else{
selectedData.splice(index,1);
}
para.textContent = "";
para.innerHTML = selectedData ;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="table">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
</table>
<h3> Selected Data: </h3>
<p id="selectedData"></p>
Updated to meet your needs.
create a function to build the array values based on looking for any checked inputs then going to their parents and grabbing the sibling text values
attach your change event to the checkbox click even.
I provided a fiddle below that will output the array in the console.
function buildTheArray(){
var thearray = [];
$("input:checked").parent().siblings().each(function(){
thearray.push($(this).text());
});
return thearray;
}
$("input[type='checkbox']").change(function(){
console.log(buildTheArray());
});
Fiddle:
http://jsfiddle.net/gcu4L5p6/

Select random row from table, then remove that row and create a new table with that row?

I found some code that helped me get pretty close. Kudos to daiscog for that! Here is what I'm trying to do. There is a table with rows of entries for a giveaway. I want to be able to click a button and remove that row from the table and and generate a new table on the fly with that random row that was picked form the primary table.
Right now the code below selects a random row and highlights it in dark blue. Which is great. Issue is it also counts the <thead> and <tfoot> as rows in the random pick, ideally it wouldn't. Which isn't a huge deal. But can be once I get working what I'd like to. Issue is right now when the logs of entries gets really long it's hard to keep track of who was picked first.
Any ideas on how to accomplish this via Javascript?
<table id="cp_logs_table" class="widefat" style="background-color:#333;color:#ddd;font-weight:bold;margin:15px;">
<thead><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></thead>
<tfoot><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></tfoot>
<tr>
<td title="wolfkin">wolfkin [wolfkin]</td>
<td>- 150</td>
<td>
Lottery Ticket
</td>
<td title="2011-10-14 17:20:29">11 hours ago</td>
</tr><tr>
<td title="dragon290513">dragon290513 [dragon290513]</td>
<td>+ 5</td>
<td>
Video Entry
</td>
<td title="2011-10-14 01:42:30">1 day ago</td>
</tr></table>
<script>
function cplottopickwinner() {
// get all TRs that are descendants of table#cp_logs_table:
var tds = document.getElementById("cp_logs_table").getElementsByTagName("tr");
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight tr at that index
tds[rand].style.backgroundColor = "#375297";
//tds[rand].style.color = "#000";
}
</script>
Pick Random Winner(s)
I modified the function to the code below, but it's not populating the table with anything, but it's still highlighting the table row in blue. I'm sure I'm missing something simple to automatically remove that row and add it to the new table.
function cplottopickwinner() {
// get all TRs that are descendants of table#cp_logs_table:
var tds = document.getElementById("cp_logs_table").getElementsByTagName("tr");
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight tr at that index
tds[rand].style.backgroundColor = "#375297";
//tds[rand].style.color = "#000";
jQuery("#cb_winners").fadeIn("slow");
var html = tds[rand].html();
tds[rand].remove();
jQuery("#winners").append("<tr>"+html+"</tr>");
}
If you have another table to put in the winners,
<table>
<thead><!-- .... --></thead>
<tfoot><!-- .... --></tfoot>
<tbody id="winners"></tbody>
</table>
Then you just have to append the whole <tr> to it, then it will disappear from old table because it is not cloned.
document.getElementById('winners').appendChild(trs[rand]);
http://jsfiddle.net/sMPQS/
I made it using jQuery.. hope it's helpful.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<table id="cp_logs_table" class="widefat" style="background-color:#333;color:#ddd;font-weight:bold;margin:15px;">
<thead><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></thead>
<tfoot><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></tfoot>
<tr>
<td title="wolfkin">wolfkin [wolfkin]</td>
<td>- 150</td>
<td>Lottery Ticket</td>
<td title="2011-10-14 17:20:29">11 hours ago</td>
<td><input type='submit' value='MOVE' class='move'></td>
</tr>
<tr>
<td title="dragon290513">dragon290513 [dragon290513]</td>
<td>+ 5</td>
<td>Video Entry</td>
<td title="2011-10-14 01:42:30">1 day ago</td>
<td><input type='submit' value='MOVE' class='move'></td>
</tr>
</table>
<script>
$('.move').click(function(){
var row = $(this).parent('td').parent('tr');
var html = row.html();
row.remove();
$('#winners').append("<tr>"+html+"</tr>");
});
</script>
<table id='winners' ></table>

Get the closest class from a list jquery

It's hard to explain, so I created an example:
jsfiddle
My idea is to change the color of each column when the respective input is in action...
If anyone has a better idea to do this - please let me know!
When I focus the input, I need the current class of the column.
first column input, get the class of the RED column
and the second one, get the class of the BLUE column
and so go's on...
Because if I get the class, then I can manipulate anything with this class.
the code is here:
$(".inputTest").focusin(function(){
var class = $(this).closest('.tableList')
.children().children().children('.auxClass')
.attr('class')
.split(' ')[0];
alert(class);
});
This is the main code, I try alot of stuffs to get, but nothing.
Thanks
First I'd add an outer table to split the page in a left and a right hand side. That way, the inputs below the red border and the inputs below the blue border each have their own table.
Then you can search for the first td below the closest table:
$(".inputTest").focusin(function(){
var class = $(this).closest('table').find('td:eq(0)').attr('class');
alert(class);
});
Click for working jsfiddle example.
Try this:
$(".inputTest").focus(function(){
var class = $(this).closest('table').parent().attr('class');
alert(class);
});
Edit: Oh, i just realised your inputs are not inside your tables, i think you're gonna have a hard time matching them up to the table/column they're under then. You'd need to add a common attribute to identify them by.
As mentioned in other answers your inputs are not actually in the same "columns" as your red/blue bordered tables, but you can make it so they are using the <col> element on the main table, then using the index value you can match your inputs to their column
Working Example
HTML - the only addition is the two <col> elements at the start
<table width="100%" border="1" class='tableList'>
<col span="2" class="left">
<col span="2" class="right">
<tr>
<td class="101 auxClass" width="261px" colspan="2" style="border: solid red;">
<table border="1" cellspacing="1" cellpadding="1" width="100%" height="70px">
<tbody>
<tr>
<td colspan="2">Something</td>
</tr>
<tr>
<td width="78px">Something 2</td>
<td>Total</td>
</tr>
</tbody>
</table>
</td>
<td class="102" width="261px" colspan="2" style="border: solid blue;">
<table border="1" cellspacing="1" cellpadding="1" width="100%" height="70px">
<tbody>
<tr>
<td colspan="2">
Something 3
</td>
</tr>
<tr>
<td width="78px">Something 4</td>
<td width="75px">Total 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
<td>Result</td>
<td><input type="text" class="inputTest"/></td>
</tr>
</table>
CSS:
col.current {background: #eee;}
jQuery
$(".inputTest").focusin(function(){
var colidx = $(this).closest('td').index();
if (colidx == 1) {
$("col").removeClass('current');
$("col.left").addClass('current');
} else if (colidx == 3) {
$("col").removeClass('current');
$("col.right").addClass('current');
}
});
Your main table is actually 4 columns, and you need to split it into two halfs of two columns each with the input being in the second column of each half
The jQuery is finding the index of the parent td of the input - there are four columns in the main table so the index of a td will either be 0,1,2 or 3 - and the input is either going to be in cell index 1 or cell index 3. When it finds out which one it add a class to the relevant col element to which you can add a background highlight..
Note though that the CSS you can apply to a col element is limited, see: http://www.quirksmode.org/css/columns.html , for the options so it would depend what you want to do
however I think from this you could probably target td index 0 & 1, or td index 2 & 3 if needed

Categories

Resources