I have a table and a function.
I can take cell's parameters.
I'm new in JS. Please help to find index of current cell. Thank you
function changePosition(currentCell) {
let top = currentCell.offsetTop
//need to find index of cell
}
<table class="square-table">
<tr>
<td onmouseover =
"changePosition(this)"></td>
<td onmouseover =
"changePosition(this)"></td>
<td onmouseover =
"changePosition(this)"></td>
<td onmouseover = function() {
"changePosition(this)"></td>
</tr>
</table>
I found the solution here
link
function changePosition(currentCell) {
let top = currentCell.offsetTop
currentCell.cellIndex
//need to find index of cell
}
My problem is resolved. Sorry
Related
I have a table in html and I want to alter the text inside different cells using js. My table looks like this:
<tr><td colspan="7" style="text-align:center;">Calendar evenimente tds</td></tr>
<tr>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
<th>Data5</th>
<th>Data6</th>
<th>Data7</th>
</tr>
<tr>
<td id="col1row1">null</td>
<td id="col2row1">null</td>
<td id="col3row1">null</td>
<td id="col4row1">null</td>
<td id="col5row1">null</td>
<td id="col6row1">null</td>
<td id="col7row1">null</td>
</tr>
</table>
and my js script looks like this:
var j=0;
for(j=0;j<=7;j++)
document.getElementById("col"+j+"row1").innerHTML=j;
but I get this error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
My question is whats the propper way of modifying the text inside a HTML table cell and what am I doing wrong?
The first iteration of your loop fails because there is no col0. Rather than iterate over IDs like this, you can simply loop over the elements by tag:
Array.from(document.getElementsByTagName('td')).forEach((td, index) => {
td.innerHTML = index
})
If you want the count to start at 1, use td.innerHTML = index + 1 instead.
loop are calling an ID that does not exist.make for loop starts with 1 instead of zero as there is no col0row1 in your html
var j;
for(j=1;j<=7;j++){
document.getElementById("col"+j+"row1").innerHTML=j;
}
As at j = 0 there is no element with id "col0row1" hence the uncaught error.
var j = 1
for(j=1;j<=7;j++){
document.getElementById("col" + j + "row1").innerHTML = j;
}
In my webpage I am populating a table using handlebars and getting the values from a db:
<table>
<tbody id="myDiv">
{{# each alarms}}
<tr class="row100 body">
<td class="cell100 column1">{{ this.alm_id }}</td>
<td class="cell100 column2>{{ this.message }}</td>
<td class="cell100 column3">{{ this.level }}</td>
</tr>
{{/each}}
</tbody>
</table>
Now I want that rows to be clickable and to open a particular popup depending on the row (there will be a description of that row).
So I wrote this:
<script>
var modal_exp = document.getElementById('myModal_explanatory');
var btn_exp = document.getElementById("myBtn_exp");
var span_exp = document.getElementById("close_exp");
btn_exp.onclick = function() { modal_exp.style.display = "block"; }
span_exp.onclick = function() { modal_exp.style.display = "none"; }
window.onclick = function(event) {
if (event.target == modal_exp) { modal_exp.style.display = "none"; }
}
</script>
The popup works well when called outside the table.
Inside the table it doesn't work and the problem is that I'm assigning the same id to every row and it doesn't know which one is referring to.
I have no idea how to solve this.
The idea is to have a different id for every row (that can be achieved using handlebars, e.g. id="myBtn-{{this.id}}" but then I don't understand how to assign it to my bin_exp variable inside the script.
An approach using classes would work much better over IDs. Classes are a great way to apply an identifier to similar elements. In this case you need a way to apply a click event to multiple btn-exp.
To pass the data to the element, leverage to data attribute on the element. You can pass what ever data from handle bars you need into the attribute an later access in JavaScript.
<table>
<tbody id="myDiv">
{{# each alarms}}
<tr class="row100 body">
<td class="cell100 column1">
<!-- Class will be used to select all .btn_exp and from their events you can access the unique data -->
<a href="#" class="btn_exp" data-alm-id="{{this.alm_id}}">
{{ this.alm_id }}
</a>
</td>
<td class="cell100 column2>{{ this.message }}</td>
<td class="cell100 column3">{{ this.level }}</td>
</tr>
{{/each}}
</tbody>
</table>
var modal_exp = document.getElementById('myModal_explanatory');
var btn_exp = document.querySelectorAll('.btn_exp'); // This returns a NodeList of the .btn_exp objects
var span_exp = document.getElementById("close_exp");
span_exp.onclick = function() { modal_exp.style.display = "none"; }
btn_exp.forEach(function(button) {
button.addEventListener('click', function(event) {
// Through the event object you can get the unique instance of .btn_exp that you clicked
var button = event.currentTarget
modal_exp.style.display = "block";
// If you wanted to get the data-alm-id value for this specific button you can access it like this
var button_alm_id = button.dataset.almId // dashes are converted to Camel case
// ... Do what ever you want with this value
});
});
For more info on querySelector() and querySelectorAll() checkout the MDN here https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
I am validating a drill down process in the portal i am testing, for this my script is doing:
Read the value from the first row of a table and click at this value (there is a link for certain cells that perform the drill down to the detail page)
To click at this particular cell I am using it's ID:
<table id="transHistTable" class="table table-hover table-bordered table-striped dataTable no-footer" style="width: 100%" role="grid" aria-describedby="transHistTable_info">
<thead>
<tbody>
<tr role="row" class="odd">
<td id="0-0" class="ng-scope">31 Jul 2018</td>
<td id="0-1" class="ng-scope">RandomText0</td>
<td id="0-2" class="ng-scope">RandomText1</td>
<td id="0-3" class="ng-scope">EmptyValue</td>
<td id="0-4" class="ng-scope">Value I Click And Save it</td>
So for this table I am clicking directly to the row 0 column 4 since my data and my filters will always bring only one row, but then, comes my problem....
When the drill down is performed I never know how many rows I will have since it depends of user operations.
I need to perform a validation to compare the sum of all the values from the table displayed after the drill down with the value captured from table "transHistTable" row 0 column 4
This is the values I get after performing the Drill Down:
<table id="transHistDetailTable" class="table table-hover table-bordered table-striped dataTable no-footer" style="width: 100%" role="grid" aria-describedby="transHistDetailTable_info">
<thead>
</thead>
<tbody><tr role="row" class="odd">
<td id="0-0" class="ng-scope">Site</td>
<td id="0-1" class="ng-scope">Date</td>
<td id="0-2" class="ng-scope">Time</td>
<td id="0-3" class="ng-scope">I</td>
<td id="0-4" class="ng-scope">value 1</td>
<td id="0-5" class="ng-scope">value 2</td>
<td id="0-6" class="ng-scope">value 3</td>
<td id="0-7" class="ng-scope">12</td>
</tr></tbody>
</table>
So what I would like to do is reading all the rows (could be 0,1,2,3,4,5...) saving the value that is stored in Column 7 then after this is done, perform a sum and then comparing with the value I have saved from the first table.
My code is this one:
var rowstransHistDetail = element(by.id('transHistDetailTable')).all(by.tagName("tr"));
rowstransHistDetail.count().then(function(rcount){
//In case only 1 row is displayed
if (rcount < 3)
{
element(by.id('0-7')).getText().then(function(valueQty){
expect(valueQty).toEqual(600)
})
}
else
{
var tempValue
for (i=0; i < rcount; i++)
{
element(by.id(i+'-7')).getText().then(function(valueQty){
tempValue = Number(tempValue) + Number(valueQty)
})
}
expect(tempValue).toEqual(600);
}
});
But when I execute this, gives me a undefined value
Any ideas how to solve this please?
Thank you!!!!
It seems that you are incrementing a value in a loop before execution.
See here: https://stackoverflow.com/a/6867907/6331748
Should bee i++ instead of ++i in a loop.
Drop me a line if I'm wrong.
===========================
Edited:
Here's some code from my side:
var expectedCells = element.all(by.css('#transHistDetailTable tr td:nth-of-type(5)'));
var currentSum = 0;
expectedCells.each((eachCell) => {
eachCell.getText().then((cellText) => {
currentSum += Number(cellText);
});
}).then(() => {
expect(currentSum).toEqual(600);
});
Sorry, but wasn't able to test it. I only want to share a main idea and elaborate it.
expectedCells are all id=n-4 cells. We go through all elements and get text from them, change to the number type and add to current value. Aftermath we do an assertion.
It also looks that if statement is not necessarily.
Let me know how it works.
Two options for your issue:
1) using element.all().reduce()
let total = element
.all(by.css('#transHistDetailTable > tbody > tr > td:nth-child(8)'))
.reduce(function(acc, item){
return item.getText().then(function(txt) {
return acc + txt.trim() * 1;
});
}, 0);
expect(total).toEqual(600);
2) using element.all().getText() and Array.reduce
let total = element
.all(by.css('#transHistDetailTable > tbody > tr > td:nth-child(8)'))
.getText(function(txts){ //txts is a string Array
return txts.reduce(function(acc, cur){
return acc + cur * 1;
}, 0);
});
expect(total).toEqual(600);
How can get a row's value on mouse click or checking the checkbox preferably from the below given html table?
Here is the js for getting values for my table from a xml using spry
var ds1 = new Spry.Data.XMLDataSet("xml/data.xml", "rows/row");
var pv1 = new Spry.Data.PagedView( ds1 ,{ pageSize: 10 , forceFullPages:true, useZeroBasedIndexes:true});
var pvInfo = pv1.getPagingInfo();
Here is the Div with spry region containing the table that gets populated from pv1 (see js part)
<div id="configDiv" name="config" style="width:100%;" spry:region="pv1">
<div spry:state="loading">Loading - Please stand by...</div>
<div spry:state="error">Oh crap, something went wrong!</div>
<div spry:state="ready">
<table id="tableDg" onclick="runEffect('Highlight', 'trEven', {duration: 1000, from: '#000000', to: '#805600', restoreColor: '#805600', toggle:true}, 'Flashes a color as the background of an HTML element.')"
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="email"><b>Email</b></th>
</tr>
</thead>
<tbody spry:repeat="pv1">
<tr class="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
<tr class="trEven" name="trEven" id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying the below code but still I am not getting the alert and hence none of the answers are also not working. I know the syntax n all are everything correct, but i am not able to figure out what is the problem here!
//inside $(document).ready(function()
$("#chkbHead").click(function() {
alert("Hi");
});
My page has other tables too for aligning some contents. So when I use the below code it works perfectly on those tables except the one in the question. It might be the problem because there are only 2 tr in the table which gets populated by a spry dataset and hence not getting identified properly. May be, I am not sure, just trying to help improve my understanding
$('tr').click(function() {
alert("by");
});
The values of a Row you will get with:
$('#tableDg tbody tr').live( 'click', function (event) {
$(this).find('td').each( function( index, item ) {
if ( $(this).has(':checkbox') ) {
alert( $(this).find(':checkbox').val() );
} else {
alert( $(this).text() );
}
};
});
What exactly do you mean by value of a table row? You can get the inner html of a table row like this:
var html = '';
$('tr').click(function() {
html = $(this).html();
});
You can get attributes of the table row (e.g. it's Id) like so:
var id = '';
$('tr').click(function() {
id = $(this).attr('id');
});
Alternatively you can get the value of nested elements such as a text input like so:
var text = '';
$('tr').click(function() {
text = $(this).find('#myTextBox').val();
});
EDIT
This is how to change the checked attribute of a checkbox nested in a table row:
$('tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
EDIT
As the table rows are being loaded dynamically - the $().click() event binding method will not work, because when you are calling it - the table rows do not exist, so the click event cannot be bound to them. Instead of using $().click use the jQuery live method:
$('tr').live('click', function() {
// do stuff
});
This binds the click event to all current table rows and all table rows that may be added in the future. See the jQuery docs here
you have to use Spry Observer,
something like this:
function funcObserver(notificationState, notifier, data) {
var rgn = Spry.Data.getRegion('configDiv');
st = rgn.getState();
if (notificationState == "onPostUpdate" && st == 'ready') {
// HERE YOU CAN USE YOUR JQUERY CODE
$('#tableDg tbody tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
}
}
Spry.Data.Region.addObserver("configDiv", funcObserver);
How can I find the seq number given the id in this example?
<table>
<tr class="row_header thin_border">
</tr><tr id="id33192010101533333" seq="2">
<td>20101015</td>
<td>600</td>
<td>730</td>
<td>Click</td>
<td><a href="#" onclick='selectEditActivity("id3319201010153333");'>Click</a></td>
</tr>
<tr id="id3319201010151111" seq="3">
<td>20101015</td>
<td>600</td>
<td>730</td>
<td> <img src="/bbhtml/img/deleteAction.png"></td>
<td></td>
</tr>
<table>
<script>
function selectEditActivity(pass_id){
alert("seq# =:" + ???)
}
</script>
try this
var id = document.getElementById("divId").getAttribute("attributeId");
How to get an attribute based on an id
With jQuery :
var seq = $('#id33192010101533333').attr("seq");
Without jQuery :
vvar seq = document.getElementById("id3319201010151111").getAttribute("seq");
You can try both of them at this Fiddle.
Both options should work in any browser!
What you really want
First of all, it's better to name your custom attribute data-seq instead of seq. The HTML5 standard allows custom elements but only considers them valid when their name starts with data-.
Also, it's not a good idea to put your click handlers directly in your CSS. It's better to use the class property or some custom data-action property with a value like edit or delete and then attach an event handler when you finish loading your page. Then, look at the first ancestor that has a data-seq property and get that property.
As one demo says more than a thousand words, here's a demo :
var list = document.querySelectorAll('[data-action="delete"]');
for (var i = 0; i < list.length; ++i) {
list[i].addEventListener("click", function(e){
alert('delete ' + e.target.closest('[data-seq]').getAttribute('data-seq'));
});
}
var list = document.querySelectorAll('[data-action="edit"]');
for (var i = 0; i < list.length; ++i) {
list[i].addEventListener("click", function(e){
alert('edit ' + e.target.closest('[data-seq]').getAttribute('data-seq'));
});
}
table, td {
border : 1px solid #333;
}
td {
padding : 10px;
}
<table>
<tr class="row_header thin_border"></tr>
<tr id="id33192010101533333" data-seq="2">
<td>20101015</td>
<td>600</td>
<td>730</td>
<td>Click</td>
<td><a href="#" data-action='edit'>Click</a></td>
</tr>
<tr id="id3319201010151111" data-seq="3">
<td>20101015</td>
<td>600</td>
<td>730</td>
<td> <img src="https://i.stack.imgur.com/mRsBv.png?s=64&g=1"></td>
<td></td>
</tr>
<table>
Or, if you prefer the jQuery way, you can replace the JavaScript code with the following (much simpler) code :
$('[data-action="delete"]').click(function(e){
alert('delete ' + $(this).closest('[data-seq]').data('seq'));
});
$('[data-action="edit"]').click(function(e){
alert('edit ' + $(this).closest('[data-seq]').data('seq'));
});
See also this Fiddle and this Fiddle for the same demo on JSFiddle, respectively without and with jQuery.
Retrieve the DOM element and then get the seq attribute:
document.getElementById(id).getAttribute('seq'); // note: this will return a string, and getElementById might return null in case there is no element with the given id.
You want to use objRef.getAttribute('seq') or plan old dot notation objRef.seq