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
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;
}
I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.
I'm looking to remove the divs from a html table but retain the content?
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
I have tried:
alert($('#datatable').html().replace('<div>', ''));
But what is alerted still contains the
<div>
tags
I can't remove them from the source because they are used for other purposes.
To keep the DOM unmodified (IE: Leave the <div> tags in the source) and only modify the HTML variable you can do:
var html = $('#datatable').html();
var tags = ["<div>", "</div>"];
for (var i = 0; i < tags.length; i++) {
while (html.indexOf(tags[i]) > -1) {
html = html.replace(tags[i], "");
}
}
alert(html);
This is available as a demo at this fiddle.
The problem with your initial solution, is that JavaScript replace only removes the first occurrence of the specified string. Hence the while loop.
Use $('#datatable div').contents().unwrap() to remove the divs from the table and alert($('#datatable').html()) to show the remaining elements of the table.
var backup = $('#datatable').html();//Keep the html
$('#datatable div').contents().unwrap();//Remove divs
alert($('#datatable').html());//Show the table (without divs)
$('#datatable').html(backup);//Bring the old, full html back
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
Try this
$('#datatable').find('div').remove();
If you want to keep content try this
$('#datatable').find('div').replaceWith(function(){
return $(this).text()
});
$('#datatable').find('div').replaceWith(function(){
return $(this).text()
});
alert($('#datatable').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td><div>3</div></td>
<td><div>4</div></td>
</tr>
</tbody>
</table>
actually there are 3 common ways
1. Using the .html('') method
$("#my_element").html(''); // the quotes are important as just .html() returns the html DOM container within the target element
2. Using the .remove() method
$("#my_element #my_element_child").remove(); // removes the targeted child element
3. Using the .empty() method
$("#my_element").remove(); // similar to the .html('') method it removes all children divs
Edit It seams i have made a mistake in understanding the OP's original intention as pointed out by #JosephGarrone and hence i made the following edit.
var dom = $("#my_element").html() // get the elements DOM structure
var regex = /(<div>|<\/div>)/g; // a regex to pickup the <divs in the DOM
var div_less_dom = dom.replace(regex, '') // do something with the "<div>" free DOM
One approach, in plain JavaScript is:
// a descriptive, but ridiculously named, function,
// htmlString: String, the string of HTML from which
// you wish to remove certain element-types,
// toRemove: String, the element-type you wish to remove,
// this is passed to querySelectorAll(), so a
// CSS selector is fine, although to guard against
// '<div>' I have removed '<' and '>' characters:
function removeElementFromHTMLString(htmlString, toRemove) {
// here we create a <div> element:
let div = document.createElement('div'),
// and declare an 'empty' variable for
// later use:
parent;
// here we convert the supplied selector to lower-caase,
// and remove the '<' and '>' characters to prevent
// errors from the user supplying '<div>', converting it
// to 'div'; this does mean that the child combinator '>'
// cannot be used in the selector (as currently written):
toRemove = toRemove.toLowerCase().replace(/<|>/g,'');
// assigning the htmlString as the innerHTML of the
// created-<div>:
div.innerHTML = htmlString;
// passing the supplied selector to querySelectorAll(),
// converting the Array-like NodeList to an Array, and
// iterating over that Array with Array.prototype.forEach():
Array.from(div.querySelectorAll(toRemove)).forEach(function(elem){
// 'elem' refers to the current element in the Array of
// elements over which we're iterating:
// assigning the elem.parentNode to a variable for reuse:
parent = elem.parentNode;
// while the found element has a first child:
while (elem.firstChild) {
// we insert that first child ahead of the
// current element:
parent.insertBefore(elem.firstChild, elem);
}
// and then, once the element has no child
// elements, we remove the element from its
// parent:
parent.removeChild(elem);
});
// and then, assuming you want a HTML String without
// those elements matching the selector, we return
// the innerHTML to the calling context:
return div.innerHTML;
}
console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));
function removeElementFromHTMLString(htmlString, toRemove) {
let div = document.createElement('div'),
parent;
toRemove = toRemove.toLowerCase().replace(/<|>/g, '');
div.innerHTML = htmlString;
Array.from(div.querySelectorAll(toRemove)).forEach(function(elem) {
parent = elem.parentNode;
while (elem.firstChild) {
parent.insertBefore(elem.firstChild, elem);
}
parent.removeChild(elem);
});
return div.innerHTML;
}
console.log(removeElementFromHTMLString(document.getElementById('datatable').outerHTML, 'div'));
td {
color: orange;
}
td > div {
color: limegreen;
}
<table id="datatable">
<thead>
<tr>
<th></th>
<th>Jane</th>
<th>John</th>
</tr>
</thead>
<tbody>
<tr>
<th>Apples</th>
<td>
<div>3</div>
</td>
<td>
<div>4</div>
</td>
</tr>
</tbody>
</table>
Is there any way to select particular rows of a table as a variable and then change their styling. For example-:
<a onclick="hl(this)">1,2,5</a>
<table>
<tr>
<tr> <td>.....</td></tr>
<tr> <td>.....</td></tr>
<tr> <td>.....</td></tr>
<tr> <td>.....</td></tr>
</tr>
</table>
now what the hl function does is when i click on it the rows 1,2 and 5 should get highlighted. What i was thinking that if there is anyway i can use some sort of selection for rows by providing an index like
var m=table.rowIndex[1]
or something and then doing
m.style.background="something"
then it might work but i have no clue what to do, So please help!
If you want to pass the row numbers as a contents of the a tag:
<script>
function hl(el){
arr = (el.innerHTML).split(",")
var t = document.getElementById("tbl")
for(var i=0; i<arr.length; i++){
t.rows[arr[i]].style.backgroundColor ="yellow";
}
return false;
}
</script>
and the html
<table id="tbl">
<tr ><td >row 1</td></tr>
<tr><td>row 2</td></tr>
<tr><td>row 3</td></tr>
<tr><td>row 4</td></tr>
</table>
1,2,3
If you want for your table rows to become clickable - so not to pass the array but trigger the highlight from clicking- you gotta do this:
js
function regEvents(){
trs = document.getElementsByTagName("tr");
for (var i=0; i<trs.length;i++){
trs[i].onclick = hilite;
}
}
function hilite(){
this.style.background = "yellow";
}
html
<table id="tbl">
<tr ><td >row 1</td></tr>
<tr><td>row 2</td></tr>
<tr><td>row 3</td></tr>
<tr><td>row 4</td></tr>
</table>
and after your dom loads bind the events - so put this at the end of your html file
<script>
regEvents();
</script>
In your example markup, the table element is the next sibling after the a element. If that's really true, then:
function hl(anchor) {
var table = hl.nextSibling;
while (table && table.nodeName.toUpperCase() !== "TABLE") {
table = table.nextSibling;
}
if (table) {
var rows = table.getElementsByTagName('tr');
rows[0].className += " highlighted";
rows[1].className += " highlighted";
rows[4].className += " highlighted";
}
}
...where the class "highlighted" applies the selection styles. This assumes there are no nested tables.
More reading:
DOM2 Core
DOM2 HTML
DOM3 Core
FWIW, if you're not already using one, I'd recommend using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences for you and provide a lot of utility functionality.
It is much better to give your functions meaningful names. Also, don't use an A element when a button or some other element is more suited (e.g. a styled span). A's are for navigation (anchors and links), not for doing things.
Here's an example of what you are trying to do using the rowIdex. The removing and adding of highlighting could be put in the same loop, or you could remember the previous highlighted rows in a closure to make it a bit more efficient.
But if you're dealing with less than about 100 rows (or probably way more), it won't make any difference to perceived performance.
<script>
function hilightRows(id, rowindexes) {
var table = document.getElementById(id);
var rows;
if (table && rowindexes) {
// Remove any current highlighting
for (var j=0, jLen = table.rows.length; j < jLen; j++) {
table.rows[j].style.backgroundColor = '';
}
// Add new highlighting
for (var i=0, iLen = rowindexes.length; i<iLen; i++) {
table.rows[rowindexes[i]].style.backgroundColor = 'red';
}
}
}
</script>
<button onclick="hilightRows('t0', [1,2,5])">1, 2, 5</button>
<button onclick="hilightRows('t0', [3,0])">3, 0</button>
<button onclick="hilightRows('t0', [])">Remove highlight</button>
<table id="t0">
<tr><td>.....
<tr><td>.....
<tr><td>.....
<tr><td>.....
<tr><td>.....
<tr><td>.....
<tr><td>.....
</table>
As Lynch is saying... jquery, especially the function index().
And here it goes (just the general idea)
$('#thingtobeclicked').click(function()
{
$('.selected').removeClass('selected');
$(this).data('indices').each(function(i){
$('#myTable tr:nth-child(i)').addClass('selected');
});
});
Hope it helps someone or gets me my 2 rep-points back.. :)
I forgot to say: In order to make this work, you set the indices to be selected on the data field of the thingtobeclicked, as in:
<a href='#' id='thingtobeclicked' data-indices='1,3,5'></a>
<table id='myTable'>...
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);