Is there anyway I can get the innerHTML of the designated nth <td> in a <table> using JavaSCript?
Since my table is automatically generated, my <td>'s do not have IDs. I am using the following HTML code:
<table id="table">
<tr>
<td onmouseover="myTD()">Cell 1</td>
<td onmouseover="myTD()">Cell 2</td>
<td onmouseover="myTD()">Cell 3</td
</tr>
<tr>
<td onmouseover="myTD()">Cell 4</td>
<td onmouseover="myTD()">Cell 5</td>
<td onmouseover="myTD()">Cell 6</td>
</tr>
</table>
But how do access, for instance, Cell 5?
Thanks a lot!
var cells = document.getElementById('table').getElementsByTagName('td');
This will contain all your table cells. Use array notation to access a specific one:
cells[4]
Here's a quick demo which changes the background color:
http://jsfiddle.net/jackwanders/W7RAu/
Not sure what you want - Dom: document.getElementsByTagName("table")[0].rows[2].cells[1]
Pass the cell back to the function:
<td onmouseover="myTD(this)">Cell 1</td>
Get the innerhtml from the object:
function myTD(obj) {
alert(obj.innerHTML);
}
Can you clarify when (on load, on hovering, ...) and where (client side, server side ...) you want to do that?
If you need the cell inside myTD, just use the this keyword, which happens to be your HTMLTableCell:
function myTD() {
this.style.color="red"; // just for the example, using CSS classes is much better
}
Using just CSS you could do:
#table tr:nth-child(2) td:nth-child(2)
{
background:#ff0000;
}
jsFiddle example
function addClassToNthTD(n) {
var table = document.getElementById('table');
for (var i = 0; i < table.childNodes.length; i++;) {
var rows = table.childNodes[i];
for (var j = 0; j < tr.childNodes.length; j++;) {
n = n - 1;
if (n == 0) {
tr.childNodes[j].className = 'foo';
}
}
}
}
This line:
$('td')
Places all of the td elements in the code into a zero-based array, so the cell with 'Cell 5' as its content would be the fifth element of that array, ie:
$('td')[4]
jQuery also accepts CSS style selectors, so if you wanted to target the every second cell in a row, you could use a selector such as:
$('tr td:nth-child(2)')
Read through the selector documentation I've linked, it can come in very handy for situations like this
I have no idea what you are trying to do, but if you want to do some kind of "hover" ability, jquery can do that quite simple. i have created an example Fiddle http://jsfiddle.net/fd3GK/1/
Related
How can I get the value of an specific input field with Javascript?
Lets take this shopify shop for example: https://geekymate.com/products/magic-doormat-1?variant=18941211607138
I am trying to create a script which is automatically applying an discount code based on the quantity filled in the quantity field.
But to do that I need to be able to get the latest value of the field.
How would the code look like to get the latest/current value?
EDIT: Thank you for the hint with the question. I do know that I need to use getElementById ( For the linked page above it would be this: var x = document.getElementById("Quanity").value; ) but how do I always get the latest input automatically if the enduser is changing the value?
The other answers are also correct (using jQuery .keyup), but you can also use this solution below (which is better). This solution uses pure javascript.
The code selects the element by using .getElementById() and uses .addEventListener() to do something when input changes.
var text = document.getElementById("text");
window.onload = function() {
text.addEventListener("input", function() {
console.log(text.value);
});
}
<input id="text" />
Or you can use the following if you want a jQuery solution. This uses jQuery .bind().
$("#text").bind("input", function() {
console.log($("#text").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="text" />
keyup() function ;)
It runs each time, when user types new text.
Also, you can use input() or change() functions.
In jQuery it works like this:
$(document).on('keyup', '#InputID', function(){
//...code...
var discount = Number( document.getElementById('InputID').value )*10/100;
});
It's a Jquery function that runs on keypress. I've included a snippet below to see how it would tie in with an input field.
$('#code').keyup(function() {
var discountcode = this.value;
console.log(discountcode);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="code" type="test" />
Keyup runs every time a specific element is lifted. Imagine someone enters 'Hello'
You will see the following logged:
'H' 'He' 'Hel' 'Hell' 'Hello'
look at the code snippet. using JavaScript to get the values. and can use addEventListener to detect the change and use detectChange function to get the latest values.
var discount = [];
function detectChange() {
var table = document.getElementsByClassName("shappify_qb_grid")[0];
for (var i = 0; i < table.rows.length; i++) {
var row = "";
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (j == 1) {
row = table.rows[i].cells[j].innerHTML;
rate = parseFloat(row);
if (rate && discount.indexOf(rate) < 0) {
discount.push(parseFloat(row));
console.log('---', parseFloat(row));
}
}
// console.log('discount : ', discount);
}
}
}
detectChange();
console.log('discount : ', discount);
<table class="shappify_qb_grid" border=1>
<thead>
<tr>
<th>Qty</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Buy 1</td>
<td>0% Off</td>
</tr>
<tr>
<td>Buy 2</td>
<td>10% Off</td>
</tr>
<tr>
<td>Buy 4</td>
<td>12% Off</td>
</tr>
<tr>
<td>Buy 5</td>
<td>14% Off</td>
</tr>
<tr>
<td>Buy 6</td>
<td>17% Off</td>
</tr>
</tbody>
</table>
This work for me!
document.getElementById("text").value;
<input id="text" />
Use the document.getElementById(); -command to get the existence of the referenced element in your HTML page. Then use the same technique of assigning attributes in the original HTML coding rules.
Use document.getElementById('able').value = 'whatever';.
<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
Here I have a table with a tr in it and 4 td's.
Now, my question is, how can I compare the td.text() with the other one?
For example:
a loop that takes the text of first td and then compare it with other td's.
If it is the same, then give that td a class.
HERE: td id="td1" should get a class
BUT:
When I'm at the 3e td, the 3e td should get a class.
This code should work for you:
var tds;
$('tr').each(function(i, item){
tds = $(this).find('td');
tds.each(function(j, elem1){
tds.each(function(k, elem2){
if($(elem1)[0] != $(elem2)[0] && $(elem1).text() == $(elem2).text()){
$(elem1).addClass('cl');
}
});
});
});
FIDDLE: https://jsfiddle.net/lmgonzalves/cqa6m6va/1/
You can use this code:
function setClasses(word) {
var tds = $("tr td");
for(var i = 0; i < tds.length; i++) {
if(tds.eq(i).text() === word) {
tds.eq(i).addClass('red');
}
}
}
setClasses("test1");
jQuery selectors will be your friend here. :)
var $container = $("#tr")
$container.children().each(function() {
if (!($(this).hasClass("td")) {
var sTextVal = $(this).text();
var $currTextGroup = $container.children(":contains('" + sTextVal + "')");
if ($currTextGroup.length > 1) {
$currTextGroup.addClass("td");
}
}
});
I'll explain the logic, and then touch on one issue to be aware of . . .
Basically, this code:
Collects all of the the children of the <tr> and loops through them one at a time
If the current child does not already have a class of "td" (if it already has a "td" class, then this text has already been checked for duplicates), it retrieves the text from inside the element and searches for all of the children of the <tr> that contain that same text value
If more than one of the children in the <tr> contain that text, all of those children are given the class of "td"
The one potential issue that this solution could run into is if the text in the current element is present as part of the text in one of its siblings. For example, if the text in one sibling is "the", and it has some siblings that have text values of "then" and "there" and "the end", they will be found by :contains.
If your text values are sufficiently "patterned" (as they are in your example), though, this should not be an issue. If it is an issue, there is a more complex way to do that "common text" selection, but I won't bother with that, unless it is necessary.
If I understand correctly, you want to select the first 'td' in a 'tr' and compare it against the other 'td' in your table. Please try the below code and let me know if it works for you.
HTML (provided by OP)
<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
CSS
.color--red { color: red; }
jQuery
$(document).ready(function(){
var first = $("#tr1 :first-child").html();
$('#tr1 :not(:first-child)').each(function() {
if(first == $(this).html()){
$(this).addClass("color--red");
}
});
});
I tried to keep it as simple as possible. The variable first pertains to that first 'td' that you want to use for comparison. Note how the each function operates on 'all elements except the first child in the tr', which clearly will omit the first variable we declared initially. From there it's all about comparing using $(this).html() to grab the value of the currently selected element, against the value obtained from the first variable.
Once this succeeds, simply add a class of your choice. For simplicity's sake, I added my own color--red class to the mix, which should show red color text for the third 'td' element as you suggested in your question post. Enjoy! Let me know if you need anything further.
I'm just getting started learning JavaScript, and I am having some trouble inserting cells into a table. I have a 1-row table of 3 cells and I want to insert a new cell to the left of whichever cell is clicked, but only after when I click on the "Insert" button.
Here is the HTML for the table:
<table border="1" id="table1">
<tr id="row1">
<td id="c1" onclick="c1()">Cell 1</td>
<td id="c2" onclick="c2()">Cell 2</td>
<td id="c3" onclick="c3()">Cell 3</td>
</tr>
</table>
<br>
<button onclick="insert()">Insert</button>
If I manually designate the cell index like I did with Cell 2, it works fine, but if I try to detect the cell's index like I'm doing with Cell 3, it just inserts the new cell at index 0.
JavaScript:
var cell1=false,
cell2=false,
cell3=false,
x;
function c1() {
cell1=true;
}
function c2() {
cell2=true;
}
function c3() {
cell3=true;
x=getElementById("c3").cellIndex;
}
function insert() {
if (cell1==true) {
// Not used yet
}
if (cell2==true) {
document.getElementById("table1").rows[0].insertCell(1).innerHTML="New1";
}
if (cell3==true) {
document.getElementById("table1").rows[0].insertCell(x).innerHTML="New3";
}
cell1=false;
cell2=false;
cell3=false;
};
I've tried a few variants both in the c3() function and in the insert() function, but each time it either didn't insert at all, or it inserts at index 0.
By the way, I'm trying to do this with pure JavaScript.
You need to check your Javascript console for errors, it reports:
Uncaught ReferenceError: getElementById is not defined
Change getElementById in c3() to document.getElementById to fix this.
<table>
<tr>
<td>foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get(this);"></td>
</tr>
<tr>
<td>foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get(this);"></td>
</tr>
</table>
Goal: To get buttons button1 and button2 to trigger the same function get() which should get the value of the first <td> in the same <tr> the button resides in. Which is, in this case: foo1 and foo2 respectively.
This is a rough outline of the function which should help understand what I'm trying to achieve-
function get(element){
alert(element.tr.first_td.innerHTML);
}
I realize there was a jQuery solution to a similar problem. But I do not understand jQuery well enough to translate it back to JavaScript. If it is possible at all using JavaScript, please show me how.
Crawl up the parentNode twice to get to the tableRow element. From there, access the first td from the HTMLCollection of cells, and get the innerHTML value:
function find( element ) {
alert( element.parentNode.parentNode.cells[0].innerHTML );
}
Fiddle: http://jsfiddle.net/jonathansampson/WuWnw/
Try this, since you have many tr and td tags right, so, you can do DOM Parsing. But you need to specify one ID for the table to get that table. For now lets call it foo-table.
var table = document.getElementById("foo-table");
var cells = table.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
If you don't wanna give an ID and you are sure that there is only one table, then use this:
var table = document.getElementsByTagName("table");
var cells = table[0].getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
alert(cells[i].innerHTML);
}
Enjoy! Hope this helps! :) No jQuery or any other plugin. Pure JavaScript. :)
<table>
<tr>
<td id="button1_value">foo1</td>
<td>bar1</td>
<td><input type="button" id="button1" onClick="get('button1_value');"></td>
</tr>
<tr>
<td id="button2_value">foo2</td>
<td>bar2</td>
<td><input type="button" id="button2" onClick="get('button2_value');"></td>
</tr>
</table>
You shoul identify what you want to get using an ID so that you can easily retrieve it. This also helps prevent the chance of getting erroneous data. If you give the component an id you should be able to use document.getElementById() to get that component.
function get(element){
var obj = document.getElementById(element)
alert(obj.innerHTML);
}
I've been messing around with different forms and tables, now I need something that takes data from table tr and td field, runs a if statement on each fetched item, and outputs text inside the form, depending what was found in td fields.
So right now I have something like this, which doesn't do anything useful at all, for now, just outputs td-01 class values into the form:
var test;
$('tbody tr').each(function(index) {
test = $(this+'.td.td-0');
$('fieldset.csc-mailform').after($('td.td-0'));
});
and my table structure looks something like this:
<table class="contenttable contenttable-3 tabel">
<tr class="tr-even tr-0">
<td class="td-0">01</td>
<td class="td-1">Valik 1</td>
<td class="td-last td-2">150€</td>
</tr>
<tr class="tr-odd tr-1">
<td class="td-0">01</td>
<td class="td-1">Valik 2</td>
<td class="td-last td-2">50€</td>
</tr>
<tr class="tr-even tr-2">
<td class="td-0">01</td>
<td class="td-1">Valik 3</td>
<td class="td-last td-2">170€</td>
</tr>
<tr class="tr-odd tr-3">
<td class="td-0">01</td>
<td class="td-1">Valik 4</td>
<td class="td-last td-2">88€</td>
</tr>
</table>
Right now it only find tr tags and outputs all of them. I need it to split the tr tag up, run if condition on td-0 to determine if it needs to be radio button/text input/checkbox etc, then see what td-1 contains and make that field name, then td-2 is for example a price. all of this should end up in a form.
So as you can see, I am stuck with jQuery, but I think it should be doable.
edit:
I got something like this after messing around a little, but my if statements don't seem to work on jQuery objects, any way to get around this?
var check1;
$('tbody tr').each(function(index) {
//test = $(this+'.td.td-0');
check1 = $('td.td-0');
alert(check1);
if(check1=='01'){
content_type="checkbox";
}else if(check1=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type);
//$('fieldset.csc-mailform').after($('td.td-0'));
});
//edit2
Ugh, I was running if statement against jQuery object, of course it didn't work.
I got it working with this, looks quite nasty, but it seems to work:
$('tr').each(function () { var val = $(this).children('td:first').text();
//$check1 = $('td.td-0');
if(val=='01'){
content_type="checkbox";
}else if(val=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type + '<br/>');
}
);
Now, I need to figure out how to create input fields from these.
You could possibly make it a bit cleaner by using the jQuery selector context, e.g.:
$('tr').each(function () {
var val = $('td:first', this).text();
..
}
Something like this will do:
$('table tr').each(function() {
$tds = $(this).children();
for(var i=0;i<$tds.length;i++){
$td = $tds[i];
if($td.hasClass('td-0'){
//do your thing by getting next TD or something else
break;
}
}
});