Trying to pull table header field using closest and .find functions - javascript

I am trying to pull the header field on a table so that I can manually adjust the size of the field. The header that I am trying to get to has the data-dynatable-column of "paymentStatus". Here is the function that checks for each tied to a particular table:
$("#DetCheckResults td").each(function () {
var xyzh = $(this).html();
var tdId = $(this).closest('th').find(".dynatable-head").text();
alert("Value of tdId field is " + tdId) ;
xyzh = xyzh.replace(/,/g, "");
if ($.isNumeric(xyzh))
{
$(this).css("text-align", "right");
}
if (tdId === "paymentStatus")
{
$(this).css("width", "10%");
}
});
Here is a description of the table:
<table class="tablesaw tablesaw-stack table-responsive" id="detailCheck_search_results" data-tablesaw-mode="stack">
<thead>
<tr>
<th class="dynatable-head" data-dynatable-column="transmittal"><a class="dynatable-sort-header" href="#">Transmittal</a></th>
<th class="dynatable-head" data-dynatable-column="naid"><a class="dynatable-sort-header" href="#">NAID</a></th>
<th class="dynatable-head" data-dynatable-column="transmittalTotal"><a class="dynatable-sort-header" href="#">Transmittal Total</a></th>
<th class="dynatable-head" data-dynatable-column="checkNumber"><a class="dynatable-sort-header" href="#">Check Number</a></th>
<th class="dynatable-head" data-dynatable-column="payeeId"><a class="dynatable-sort-header" href="#">Payee ID</a></th>
<th class="dynatable-head" data-dynatable-column="paymentStatus"><a class="dynatable-sort-header" href="#">Payment Status</a></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">SFF CB 16 00005</td>
<td style="text-align: left;">CASANDI500</td>
<td style="text-align: right;">7,181.42</td>
<td style="text-align: right;">403053601263</td>
<td style="text-align: left;">XXXXX0934</td>
<td style="text-align: left;">A</td>
/tr>
/table>
Can you look at the definition of the 'tdId' field to see how I can pull the header correctly. Thanks

You are traversing the table dom incorrectly. The th element you are looking for is not a direct ancestor of the td you are operating on.
You need to do:
$(this).closest("table").find("th").eq($(this).index());
and to reference the data-id you need to do:
tdId.data("dynatable-column") === "paymentStatus"
See this jsfiddle (I change the style change to a color to easily see the change)
https://jsfiddle.net/algorithmicMoose/p3L3bov2/

Related

how would i count the frequency of a unique word occurring in each table row an show that count in a selected cell on the same row?

i am working on a class assessment where we are to create a weekly schedule for a HR admin to manage staff exposure to their office during covid. i am using a html table and appending rows to the body when a new staff member is entered into the schedule.
<table class="schedule" id="adminTable">
<thead>
<tr>
<th colspan="1" id="title"></th>
<th colspan="2" id="monday1">Monday</th>
<th colspan="2" id="tuesday1">Tuesday</th>
<th colspan="2" id="wednesday1">Wednesday</th>
<th colspan="2" id="thursday1">Thursday</th>
<th colspan="2" id="friday1">Friday</th>
<th colspan="1" id="hours">Hours</th>
<th colspan="1" id="delete">Delete</th>
</tr>
</thead>
<tbody id="adminBody">
<!--tbody to dynamically append table rows-->
</tbody>
<tfoot>
<th id="time">Time</th>
<th>8am-12pm</th>
<th>1pm-5pm</th>
<th>8am-12pm</th>
<th>1pm-5pm</th>
<th>8am-12pm</th>
<th>1pm-5pm</th>
<th>8am-12pm</th>
<th>1pm-5pm</th>
<th>8am-12pm</th>
<th>1pm-5pm</th>
<th colspan="2" id="totalHours">Total Hours:</th>
</tfoot>
</table>
i am appending the draggable dive to the td cell with the code below. this could contain the words "office" or "Home".
const save = document.getElementById('saveButton');
save.addEventListener('click', () => {
var eventName = eventInput.value;
var wrap = $('<div draggable="true" ondragstart="drag(event)">').attr('id', 'count' + counter).attr('class', 'draggable').text(eventName.toLowerCase());
addCell(adminTable, rIndex, cIndex, wrap);
eventModal.style.display = "none";
document.getElementById("eventTitleInput").value = "";
counter++;
localStorage.setItem('admin1', adminBody.innerHTML);
});
if i add multiple staff and multiple div's containing the word "office", how would i count the occurrence of "office" in each individual row and then display that in the hours cell on each individual row?
i know this will be something to do with iterating over the cells in each row but everything i have tried and looked at online does not seem to work, any help would be appreciated.
thanks.

jQuery Find <th></th> which are not empty with Certain Class Name

I have a script that was working to parse a table to json.
It worked fine like this
<thead id="itemspecthead" class="itemspectheadc">
<tr>
<th class="ishead isheadname">Name</th>
<th class="ishead isheadvalue">Value</th>
</tr>
</thead>
With the script logic:
var headers = [];
$(rows.shift()).find('th:first:not(:empty), th:nth-child(2):not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
But trying to stylize my table, I added a couple other rows to my table header.
<thead id="itemspecthead" class="itemspectheadc">
<tr><td colspan="2" class="tdheader"><span>Item Specifics:</span></td></tr>
<tr><td colspan="2" class="speccaption"><span>(Generated from Unique Values from All Listings)</span><br /></td></tr>
<tr>
<th class="ishead isheadname">Name</th>
<th class="ishead isheadvalue">Value</th>
</tr>
</thead>
If I remove the two extra rows in my thead, the script works fine.
It seems the error is in this logic .find('th:first:not(:empty), th:nth-child(2):not(:empty)')
I've tried changing it to .find('th.ishead:first:not(:empty), and .find('.ishead th:first:not(:empty), to find it via classname with no luck.
How can I target my ishead th rows while keeping the extra colspan="2" rows in my thead?
Here's my onclick function that is now returning name,value,name,value (duplicating it twice for some reason..). This is literally my entire on click function script, I removed everything else.
$(document).on('click', '#editjson', function() {
var headers = [];
$('th.ishead:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
alert('headers: ' + headers);
console.log(headers);
});
returns name,value,name,value...
Apply :not(:empty) directly to all th (not on any particular-one)
Do like below:-
$(rows.shift()).find('th.ishead:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
Working sample:-
$(document).ready(function(){
var headers = [];
$('th.ishead:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
console.log(headers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead id="itemspecthead" class="itemspectheadc">
<tr><td colspan="2" class="tdheader"><span>Item Specifics:</span></td></tr>
<tr><td colspan="2" class="speccaption"><span>(Generated from Unique Values from All Listings)</span><br /></td></tr>
<tr>
<th class="ishead isheadname">Name</th>
<th class="ishead isheadvalue">Value</th>
</tr>
</thead>
</table>

How can I target a table cell in the same row with jQuery?

I have a table with a single input field and an AJAX script that runs when the input field value is modified. This is all working well. I now need to extend this to insert a date into another cell in the same row, but now sure how to target this as the ID will have to be dynamic. Here's the current table:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>
I need to insert the current data into the Order Data cell when the AJAX script is run, something like this:
$("#85759.OrderDate").html('current date');
but not sure how to dynamically target the Order Data cell? I'm setting the ID for the Order Data cell to be the same ID as the input field with ".OrderDate" appended. Current script is:
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
$this = $(this);
$.post('updateOrder.php', {
type: 'updateOrder',
recid: recid,
conNote: conNote
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Con Note Number - ' + ajaxError;
$this.closest('td').addClass("has-error");
$("#serialNumberError").html(errorAlert);
$("#serialNumberError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Con Note Number - AJAX request error. HTTP Status: ' + httpStatus;
$this.closest('td').addClass("has-error");
//display AJAX error details
$("#serialNumberError").html(ajaxError);
$("#serialNumberError").show();
});
});
});
You can get the parent element 'tr' and then find the 'td.OrderDate', I suggest you to use a class to identify the td in the context of its parent.
$(function () {
$("input[type='text']").change(function() {
var parent = $(this).parents('tr');
// Get any element inside the tr
$('td.OrderDate', parent).text('[current date]')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>987654</td>
<td id="85760.OrderDate" class="OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</table>
You can select the cell by $this.closest('tr').children('td[id$="OrderDate"]').
You can simplify it more by:
Instead of using attribute ends with selector ([id$=".."]), if you can, add a CSS class "OrderDate" for example to all the order date cells, and simplify the selector to $this.closest('tr').children('.OrderData')
Instead of closest() use parents(). This is a micro-optimization. The only difference is that closest tests the actual element itself for matching the selector, and in this case you know you only need to check parent elements
You can also optionally rely on the fact that the cells are siblings and instead of children use siblings like like$this.parents('td').siblings('.OrderDate')
Check the code below. I've removed the ajax call and replaced it with the success block, but the concept is still the same. It gets the cell that has an id that ends with "OrderDate" on the same row and sets the html for that cell. I've used the jQuery Ends With selector for this.
$(document).ready(function() {
$("input[type='text']").change(function() {
var recid = $(this).closest('td').attr('id');
var conNote = $(this).val();
var $this = $(this);
$this.parents('tr:first').find("td[id$='OrderDate']").html(new Date());
$this.closest('td').addClass("has-success")
$this.closest('td').removeClass("has-error");
});
});
.has-success {
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">Order Number</th>
<th class="text-center" scope="col">Order Date</th>
<th class="text-center" scope="col">Con Note</th>
</thead>
<tbody>
<tr>
<td>123456</td>
<td id="85759.OrderDate"></td>
<td id="85759"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
<tr>
<td>987654</td>
<td id="85760.OrderDate"></td>
<td id="85760"><input type="text" class="form-control" placeholder="Con Note" name="conNote" value=""></td>
</tr>
</tbody>
</table>

jquery hide columns in table based on dropdown select

I have a 6-column table. It has a dropdown menu so that viewers can select one of the four right-most columns (the "th"'s for those four columns are choiceA, choiceB, choiceC, choiceD). I want only the selected column to display; the other three non-selected columns would be hidden. The two left-most columns would always be visible.
i.e., The viewer would see only three columns in total (plus the dropdown of course). If she chooses, e.g., "Choice A, lbs" from the dropdown, the idea is to show the whole choiceA column and hide all the others.
I thought this would be a simple parent/child issue, but it has proved anything but simple. I have tried to map the dropdown options to the column heads for the choices
This is my jquery Code (bear in mind, I'm a beginner):
$(document).ready(function () {
$('#ddselect').change(function () {
var id = $(this).children(':selected').attr('id');
$('#' + id + '-sel').show().siblings('th.substance').hide();
$('.' + id + '-substance').show().not($('.' + id + '-substance')).hide();
});
});
This is the HTML:
<table>
<tr>
<th scope="col" align="left"></th>
<th scope="col"></th>
<th colspan="4" scope="col">
<select id='ddselect'>
<option class='ddselect' id="ChoiceA">ChoiceA, lbs</option>
<option class='ddselect' id="ChoiceB">ChoiceB, oz</option>
<option class='ddselect' id="ChoiceC">ChoiceC, oz</option>
<option class='ddselect' id="ChoiceD">ChoiceD, oz</option>
</select>
</tr>
<tr>
<th scope="col" align="left">Module</th>
<th scope="col" align="left">Units</th>
<th class='substance' id='ChoiceA-sel' scope="col">ChoiceA</th>
<th class='substance' id='ChoiceB-sel' scope="col">ChoiceB</th>
<th class='substance' id='ChoiceC-sel' scope="col">ChoiceC</th>
<th class='substance' id='ChoiceD-sel' scope="col">ChoiceD</th>
</tr>
<tr>
<td>type1</th>
<td>5,000</td>
<td class='ChoiceA-substance'>0</td>
<td class='ChoiceB-substance'>0</td>
<td class='ChoiceC-substance'>0</td>
<td class='ChoiceD-substance'>0</td>
</tr>
<tr>
<td>type2</th>
<td>545</td>
<td class='ChoiceA-substance'>288</td>
<td class='ChoiceB-substance'>8</td>
<td class='ChoiceC-substance'>9</td>
<td class='ChoiceD-substance'>0.2</td>
</tr>
<tr>
<td>type3</th>
<td>29</td>
<td class='ChoiceA-substance'>15</td>
<td class='ChoiceB-substance'>89</td>
<td class='ChoiceC-substance'>43</td>
<td class='ChoiceD-substance'>9.9</td>
</tr>
</tr>
I can show the right column head with the dropdown and hide the others, but cannot hide the "td"s that correspond to the hidden heads. (I would post a stack snippet, but the button is not appearing in my editor.)
Any ideas?
Let's break this down into a small sized example. It's better not to over complicate your code when you're working with concepts you don't fully grasp yet.
A good way to achieve what you want is to use common classes, and cross classes to pick and choose the right columns.
The code becomes much cleaner this way:
http://jsbin.com/megicegupa/1/edit?html,js,output
$('#sel').on('change', function () {
var val = $(this).val(),
target = '.' + val;
$('.choice').hide();
$(target).show();
});
<select id="sel">
<option value="one">1</option>
<option value="two">2</option>
</select>
<table>
<tr>
<th>Module</th>
<th>Units</th>
<th class="choice one">Choice One</th>
<th class="choice two">Choice Two</th>
</tr>
<tr>
<td>type1</td>
<td>5000</td>
<td class="choice one">100</td>
<td class="choice two">200</td>
</tr>
<tr>
<td>type2</td>
<td>350</td>
<td class="choice one">40</td>
<td class="choice two">90</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Side note: You have some <td> tags that are followed by </th> tags. Make sure to validate your HTML for errors.
According to your code while loading the page we can see both column names "Choice One" and "Choice Two". So it's better to hide the column name on page load.
$('#sel').on('change', function() {
var val = $(this).val(),
target = '.' + val;
$('.choice').hide();
$(target).show();
});
/*Add below code for showing column name accordingly to select box change
*/
$('.choice').hide();
if ($('#sel').val() == 'one') {
$('.one').show()
} else {
$('.two').show()
}

Change background-color of 1st row in the table

Below is my table that is getting populated with spry dataset
Here is my dataset
var ds1 = new Spry.Data.XMLDataSet("/xml/data.xml", "rows/row");
Here is my jquery inside a method that is called on a button click
function addRow()
{
var newRow = new Array();
var nextID = ds1.getRowCount();
newRow['ds_RowID'] = nextID;
newRow['id'] = "x";
newRow['name'] = "Abhishek";
newRow['country'] = "India";
ds1.dataHash[newRow['ds_RowID']] = newRow;
ds1.data.push(newRow);
Spry.Data.updateRegion(ds1);
ds1.sort('name','descending');
ds1.setCurrentRow(newRow.ds_RowID);
$(".trEven td").css("background-color", "red");
alert($.fn.jquery);
/*$("#tableDg tbody tr:first").css({
"background-color": "red"
});*/
}
Here is my table
<div id="cdiv" style="width:100%;" spry:region="ds1">
<table id="tableDg"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="host"><b>Country</b></th>
</tr>
</thead>
<tbody spry:repeat="ds1">
<tr id="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF" class="{ds_OddRow}">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
<tr id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;" class="{ds_EvenRow}">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
</tbody>
</table>
</div>
Am I going wrong somewhere, please guide me. Thanks :)
If I remember right, <tr> is only describing structure. <td> represents visual part of the table. Or this is how some browsers renders them.
Therefore $("#trEven td").css("background-color", "red") should work. And preferrably you should use classes instead of ids in these kind of cases where there may exist multiple instances.
Works for me (jsFiddle). What problems are you experiencing?
If your use classes instead of id's, you can use something like the following:
$('.trEven').each(function() {
$(this).css({"background-color": "red"});
});
See for reference: jQuery API - .each()
You shouldn’t be using ids for odd and even rows. id values are meant to be unique within the page.
So, I’d suggest:
<tr class="trOdd"
and:
<tr class="trEven"
and then:
$(".trEven")
If you really only want the first row in the table body to get a red background (as opposed to all the even ones), then your selector should be:
$("#tableDg tbody tr:first")

Categories

Resources