How to grab data from table with divs and inputs inside cells? - javascript

I am still new to js and jQuery. How would I iterate through the table and grab data from each cell (the date, and input "from" and "to")?
<table class="table table-striped table-bordered table-hover table-condensed" id="entryTable">
<thead>
<th>Date</th>
<th>First Shift</th>
<th>Second Shift</th>
</thead>
<tbody>
<tr>
<td>2/1/2016</td>
<td>
<div id="time" class="form-group">
From: <input type="text" id="start01">
To: <input type="text" id="end01">
</div>
</td>
<td>
<div id="time" class="form-group">
From: <input type="text" id="start02" >
To: <input type="text" id="end02">
</div>
</td>
</tr>
</tbody>
</table>

Here Is a Jsfiddle I built for you JsFiddle To Get table values
And the code I used is
var date = $('#entryTable').find('tbody td:eq(0)').text();
var From01 = $('#entryTable').find('tbody td:eq(1) input:eq(0)').val();
var To01 = $('#entryTable').find('tbody td:eq(1) input:eq(1)').val();
var From02 = $('#entryTable').find('tbody td:eq(2) input:eq(0)').val();
var To02 = $('#entryTable').find('tbody td:eq(2) input:eq(1)').val();
In the Fiddle I have put a button to fetch the value on click of the button, I am displaying the values in alert, you can change the code according to your requirement
- List item
EDIT: To loop through all the td's you can do this
$.each($('#entryTable').find('tbody td), function(){
var currentTdOfLoop = $(this);
//do your stuff here
});

in javascript you can use the method document.getElementById("tagId") for example in your case document.getElementById("time") or you can use document.getElementByClassName("tagClassName") or document.getElementByTagName("TagName") and each of them returns an array of dom elements in JQuery library it's so similar to css selectors for example
$("#elementId") to select an element by its id
$(".className") to select an elements by their class name
$("tagname") like $("p") to select all the p tags in the dom
$("div p") to select the p tags which in a div tag
and for example in your code you can grape a th element in your table using a selector like that $("#entryTable > thead th:nth-child(2)")
and I think that

Related

Deleting contents of last cell of html table row

I have an html table that includes rows:
<tr id="firstInRow"><td></td><td><input name="longP1" id="longP1" type="text" style="width: 70px"></td><td><input name="latP1" id="latP1" type="text" style="width: 70px"></td><td>(upper left)</td></tr>
<tr id="secInRow"><td></td><td><input name="longP2" id="longP2" type="text" style="width: 70px"></td><td><input name="latP2" id="latP2" type="text" style="width: 70px"></td><td>(lower right)</td></tr>
which creates a table like this:
latLongTable
I have already created an add row function that works, and I am trying to delete the contents of the last cells in that function. I want to remove the text "(upper left)" and "(lower right)". I tried a couple of ways, including:
var rowIn1 = document.getElementById("firstInRow");
rowIn1.deleteCell(-1);
But it doesn't work.
You can use .remove() function of jQuery.
For example:
$("#firstInRow").find("td:last-child").remove();
This will find the last column (td) of the row with id firstInRow and remove it from DOM. You can remove the other cell using the same method.
If you want to remove the content only then use:
$("#firstInRow").find("td:last-child").text('');
This will not remove the last column from DOM, instead it will clear the content from last column.
$("#clear").on("click", function() {
$("#firstInRow").find("td:last").text("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1" cellpadding="5">
<tr id="firstInRow">
<td>First</td>
<td>Last</td>
<td>Content to clear</td>
</tr>
</table>
<button type="button" id="clear">Clear last column</button>
</body>

Change class of input elements inside cloned div with drag & drop

I have two columns. The column on the left loads with rectangular divs, which inside of these divs are 5 input elements that are loaded via PHP with data. The user can drag a div from the left column over to the right column. This will clone it and the user can begin to edit the input elements. I have been able to change the ID of the parent div once its cloned but am running into trouble changing the class names of the input elements inside the cloned div. Im going to save them via ajax and will build an array of all values that belong to each classname. The cloned class names must be different from the original as not to capture the original data.
This is an example of one of the divs that a user can drag and clone. No PHP yet.
<div class='pcaccount' draggable="true" id='account' data-id='accountid' ondragstart="drag(event)" >
<table class='tablesorter'>
<thead id='accountrow'>
<th align='center'>
<input type='text' value='hello' class='owner' >
</th>
<th align='center'>
<input type='text' value='hello' class='custodian' >
</th>
<th align='center'>
<input type='text' value='hello' class='type' >
</th>
<th align='center'>
<input type='text' value='hello' class='tax' >
</th>
<th align='center'>
<input type='text' value='hello' class='accvalue' >
</th>
</thead>
</table>
</div>
This is my current JS. It works fine for dragging, dropping, cloning, and changing the ID of the parent DIV but i can't seem to be able to change the class of the input elements within the div.
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("div", ev.target.id);
var i = 0;
}
function drop(ev) {
var newId = 'newaccount';
ev.preventDefault();
var data=ev.dataTransfer.getData("div");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = newId+i;
nodeCopy.class = 'newaccount';
ev.target.appendChild(nodeCopy);
i++;
}
Iv neglected to include any code I have tried to make to accomplish this as its rubbish. Any help on this would be greatly appreciated. Also it would be necessary to change the ID of the "thead" as I want to append another table header to it once it is cloned.
Many thanks in advance.
Since you tagged the question with jQuery, here is a jQuery snippet which should allow you to modify child elements of the cloned node:
$('input', nodeCopy).each(function () {
$(this).removeClass(...).addClass(...);
});
$('thead', nodeCopy).each(function () {
$(this)[0].id = ...;
});
Without jQuery, you can achieve something similar using nodeCopy.querySelector or nodeCopy.querySelectorAll.

JQuery search bar to hide table rows

Hopefully someone will be able to help me with this. I have a dynamically created table full of info, and I am trying to use JQuery to only show rows that are matching what is being typed in the search bar. The match is of the first td within each row. I am not sure why this does not work.
JQuery
var $foo = $('#table-name tr input[name="someValue"]');
$('#search').keyup(function() {
var bar = $.trim($(this).val()).toLowerCase();
$foo.parent().parent().show().filter(function() {
var thud = $(this).val().toLowerCase();
return !~thud.indexOf(bar);
}).hide();
When entering any character in the search bar all of the rows disappear, whether or not there are any matches. The table is structured as follows:
table
<table id="table-name">
<thead>
<tr>
<th>0</th>
<th>1</th>
</tr>
</thead>
<c:forEach>
<form:form id = “{id}”>
<tr id="${id2}">
<td><input type="text" class= “someClass" name= “someValue"> </input></td>
<td><select class="someClass" name="otherValue"> </select> </td>
</tr>
</form:form>
</c:forEach>
</table>
Why is my JQuery not behaving correctly?
No need to reinvent the wheel. Try this one:
JQuery Quicksearch: http://deuxhuithuit.github.io/quicksearch/r/examples/
Your JS code becomes no more than:
$('#id_search').quicksearch('table#table_example tbody tr');
See running example: http://jsfiddle.net/ddan/tqhxqwrh/1

Select elements in each child tables one by one

I have the following html which is basically a parent table with some child tables inside it,
<table id="roottable" class="tablemain" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td></td>
<td>
<table class="intable" align="center" border="0">
<tbody>
<tr>
<td class="chn" colspan="2" align="center">
<div>
<div class="mparent">
<div class="checkbox">
<input type="checkbox" id="ch243" name="ch243" value="243">
<label for="ch243"></label>
</div>
<div class="chtext">Category</div>
</div>
</div>
</td>
</tr>
<tr>
<td>Param two</td>
<td>
<div class="checkbox">
<input type="checkbox" id="ch244" name="ch244" value="244">
<label for="ch244"></label>
</div>
</td>
</tr>
</tbody>
</table>
......
......
<table class="intable" align="center" border="0">
......
......
What I need to do is access all checkboxes of the nested table, for each table. That is get the checkboxes inside the first nested table, perform some operations with it, move to the next nested table do the same with the checkboxes inside it.
I can access individual tables like below with their id,
$('#tableid').find('input[type="checkbox"]').each(function () {
});
This works, but the tables are auto generated from db and the id is not known beforehand, also, the number of tables may vary, so I have no option other than selecting the parent table and then look for every child tables inside it one by one ... I have tried this ...
$('table').each(function(){
$(this).find('input[type="checkbox"]').each(function () {
// DO STUFFS WITH CHECKBOXES
});
But it doesn't work... How do I go about this? Thanks.
$('table tr td').each(function(){ // this line is for main outer table
$(this).children('table').each(function () { //this will iterate all the child table
$(this).find('input:checkbox').each(function(){ //this will find checkbox inside each table
//Your Stuff
});
});
});
NOTE :- I m not using id selector here because questioner mentioned that he doesn't know id's beforehand.
Working Demo
Working Demo
Your final code block looks acceptable, except that you haven't prevented the table selector from also selecting the outer table. As written, this would cause each set of checkboxes to be considered twice - once as part of its own table and again (actually first) as descendants of the outer table.
Try a more specific selector:
$('#roottable .intable').each(...)
I would do something like this:
$('#roottable').find('.intable').each(function(index, elt) {
// operate now on each "child table"
var $childTable = $(elt);
$childTable.find('input[type="checkbox"]').each(function(i, cb){
// Do your stuff with the checkoxes of the current ".intable" table
});
});
Just use:
var tableInputs = {};
$('#roottable input[type="checkbox"]').each(function () {
var id = $(this).closest('table').attr('id');
var name = $(this).attr('name');
tableInputs[id] = {};
tableInputs[id][name] = $(this).val();
});
This will select all checkboxes that are a child of a table.
EDIT if you need to group just find the id of the closest parent table and use that as an index for an object. You end up with one large object with all the id's as properties, while using only one each loop.

Accessing different types of element

I have a table with few rows. Each rows has header, data and hidden field. Data column can have either text or textarea.
<table id="knowledgeTreeTable" class="custom">
<tbody>
....................
<tr>
<th class="">What is the name of the party?</th>
<td class="">
<textarea id="ktField_7" class="ktEdit" type="text"></textarea>
</td>
<input id="ktField_7H" type="hidden" value="Unique contested">
</tr>
<tr>
<th class="">What is the name of the opposing party?</th>
<td class="">
<input id="ktField_8" class="ktEdit" type="text" style="width: 97%;">
</td>
<input id="ktField_8H" type="hidden" value="Query">
</tr>
......................
</tbody>
</table>
I am able to read the content of header and hidden field but not sure how to read data column as it can have two different types of element.
$("#knowledgeTreeTable tr").each(function() {
alert($('th', this).text());//OK
//alert($('td > [input, textarea]', this).val()); // This is not OK.
alert($('input', this).val());//OK
});
You can't group selectors like
td > [input, textarea]
Instead, use
td > input, td > textarea
Just as you would in a CSS selector, look for both:
alert($('td > input, td > textarea', this).val());
Although since you're using the same class for both, I'd be inclined to use:
alert($('td > .ktEdit', this).val());
Whenever you're trying to access a child element in a loop like this, you need to establish what the common factors between each element is. In this case they are different tags with different names, but they both have the ktEdit class, and both have type="text" (which I don't believe is actually applicable to textareas).
In this case, the common variable is the class name, so you can use that as your selector. As long as you target your parent loop correctly, it won't matter if you use that class on other elements throughout the page:
$("#knowledgeTreeTable tr").each(function() {
alert($('.ktEdit', this).val());
});

Categories

Resources