Multiple elements with same Id in Javascript - javascript

I have a case where a html file contains multiple elements with the same ID name.
The table row contains 5 columns of which I need to consider 2,3,4,5 columns data.
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
I have the above code at several places in the file. I need to add the respective values using javascript.

An ID is unique in an html page. You can call it THE ID as well wrt a page. You cannot have same ID for two different tags in a single page. But you can use class instead of and ID. Know about it here
So your HTML can be like
<tr class='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
As an example with jquery you can do something like this,
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
</table>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$(".one").eq(0).find('td').eq(0).html("I'm tracked");
// get 1st tr and get first td
$(".one").eq(1).find('td').eq(1).html("I'm tracked");
// get 2nd tr and get second td
$(".one").eq(2).find('td').eq(0).html("I'm tracked");
// get 3rd tr and get first td
});
</script>
</body>
</html>
But I guess this approach can be tedious.

Id should be unique and if you use the same id, javascript code refers only the first element. but if you still want to use same id than you may try the below code:
$(function(){
$('[id="total_row"]').each(function(){//run for every element having 'total_row' id
var $this = $(this);
$this.find('td').eq(1).text() //to get second column data
$this.find('td').eq(1).text('dummy text') //to set second column data
});
});

You can use XHTML:
<p id="foo" xml:id="bar">
Through XHTML you can apply similar ID to multiple Controls.
Similar questions can be found here:
http://www.c-sharpcorner.com/Forums/

While duplicate IDs are invalid, they are tolerated and can be worked around. They are really only an issue when using document.getElementById.
I'll guess that the table looks like:
<table id="t0">
<tr>
<td>-<th>count<th>Pass<td>Fail<td>Error<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td><td>1<td>0<td>
<tr>
<td>-<td>1<td><td>0<td>1<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
</table>
<button onclick="calcTotals();">Calc totals</button>
If that's correct, then a function to add each sub–section can be like:
function calcTotals(){
var table = document.getElementById('t0');
var rows = table.rows;
var row, totals = [0,0,0,0];
// For every row in the table (skipping the header row)
for (var i=1, iLen=rows.length; i<iLen; i++) {
row = rows[i];
// If it's a total row, write the totals and
// reset the totals array
if (row.id == 'total_row') {
for (var j=0, jLen=totals.length; j<jLen; j++) {
row.cells[j+1].innerHTML = totals[j];
totals[j] = 0;
}
// Otherwise, add values to the totals
} else {
for (var k=0, kLen=totals.length; k<kLen; k++) {
totals[k] += parseInt(row.cells[k + 1].innerHTML) || 0;
}
}
}
}

In addition to using classes, which works but feels kind of icky to me, one can also use data-* attributes.
<tr class='total_row' data-val-row-type="totals-row">
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
Then, in your script (jQuery syntax -- querySelectorAll has a similar syntax)
var $totalsRows = $("[data-val-row-type='totals-row']);
When you are in a team with a separate UI designer, this keeps the UI guy from ripping out and changing your class names to fix the new design layout and it makes it quite clear that you are using this value to identify the row, not just style it.

Related

Replace ID for all tag after cloning node by javascript

I need to change all ID after cloning node below by javascript or jquery.
<table id="1">
<tr>
<td id="RM_1"><button type="button" onclick="duplicateFunction(1)"></td>
<td id="CL_1"><input id="[1][999]"/></td>
</tr>
</table>
when I clone node with ID = "1" I need to change 1 to 2 as in all ID tags below.
<table id="2">
<tr>
<td id="RM_2"><button type="button" onclick="duplicateFunction(2)"></td>
<td id="CL_2"><input id="[2][999]"/></td>
</tr>
</table>
Remark : The table id is unique id. I use simple number to explain the code.
update
When user click duplicate button. The duplicateFunction will be called.
now , I can change table id but I can't change inside.
function duplicateFunction(table_id){
var myTable = document.getElementById(table_id);
myClone = myTable.cloneNode(true);
var newTableID = Date.now();
myClone.id = newTableID;
document.getElementById("AddingSpace").appendChild(myClone);
}
because every tags have another features to do when user click.
that's the best way on this time.
Thank you in advance
This is an attempt along the lines suggested by Rory McCrossan. Instead of the individual ids of your elements inside the table I used shortened class names. The tables do not have actual ids but dataset attributes with id properties. This way it will not cause serious problems if ids should become double ...
My function calculates a newid on the basis of the number of already existing tables in the #addingspace div. This is not production ready either but probably less problematic than your original approach.
const $trg=$('#addingspace');
$(document).on('click','.RM button',function(){
let newid=$trg.find('table').length+2;
$trg.append(
$(this).closest('table').clone().data('id',newid) // set data-id
.find('.CL span').text(newid).end() // set span and return cloned element
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table data-id="1">
<tr>
<td class="RM"><button type="button">duplicate</button></td>
<td class="CL"><input /> id: <span>1</span></td>
</tr>
</table>
<div id="addingspace"></div>

how to hide a table row in html here the condition as row values using javaScript ? If two row values are the same then hide one

I have a html table where I need to hide one row where column value is same. like if key1 and key2 have same value then hide one row.
here each row is different, in that there are two dates whose value may be same sometimes in that case i should hide one row. the data are comming in html in json format. here duplicate does not mean that two rows are completely same, no there values are same.
<html>
<header>Hide Test</header>
<body>
<pre>
<tr>
<td>Key1</td>
<td>Value1</td>
</tr>
<tr>
<td>Key2</td>
<td>Value2</td>
</tr>
<tr>
<td>Key3</td>
<td>Value3</td>
</tr>
</pre>
</body>
</html>
You can loop over all rows, save found values in an array and if a value is already in an array you will hide it instead.
var rows = document.querySelectorAll('table tr');
var foundValues = [];
rows.forEach(function(el){
console.log(foundValues);
console.log(el.children[1].innerHTML);
if(foundValues.includes(el.children[1].innerHTML)) {
el.style.display = 'none';
}
else {
foundValues.push(el.children[1].innerHTML);
}
});
<table>
<tr>
<td>Key1</td>
<td>Value1</td>
</tr>
<tr>
<td>Key2</td>
<td>Value2</td>
</tr>
<tr>
<td>Key3</td>
<td>Value2</td>
</tr>
<tr>
<td>Key4</td>
<td>Value4</td>
</tr>
</table>
Assuming the value will always be in the second field of each row I have a solution here which should work.
//we need to check that the window has loaded so we can target the elements in the DOM.
window.onload = function(){
var seen = [];
var tableRows = document.getElementsByTagName('tr');
for(i = 0; i < tableRows.length; i++){
//get the table data for this particular table row
var tableData = tableRows[i].getElementsByTagName('td');
//the value will be contained in the second td tag of the row so we retrieve it as follows:
var value = tableData[1].innerText;
//log the value to check.
console.log(value);
if(seen[value]){
//if the value already exists hide the table row that contains this value.
tableRows[i].style.display = "none";
}else{
//add the value to the 'seen' array.
seen[value] = true;
}
}
}
You can test this with the following table where two values are the same.
<!DOCTYPE html>
<html>
<head>
<title>Hide test</title>
<script>
//javascript code goes here
</script>
</head>
<body>
<table>
<tr>
<td>Key1</td>
<td>Value1</td>
</tr>
<tr>
<td>Key2</td>
<td>Value2</td>
</tr>
<tr>
<td>Key3</td>
<td>Value1</td>
</tr>
</table>
</body>
</html>

How To Grab Data In Any Table Row (HTML/JavaScript) Using Tree Traversal Methods

I have a table that looks like this -->
<table>
<tr style="display: none";><td class="index">index_value</td></tr>
<tr><td>section header</td></tr>
<tr>
<td class="name>Steven</td>
<td class="height">6 ft.</td>
<td><button class="add">Add</button></td>
</tr>
</table
and a js script that looks like this -->
<script>
$(".add").on('click', function(){
var the_name = $(this).closest("td").siblings(".name").text();
var the_type = $(this).closest("td").siblings(".type").text();
var the_index = $(this).parent().find("td.index").text();
}
</script>
As you can probably tell, I'm trying to get the values of certain td within this table. The first two variables work just fine because they are within the same table row; however, the last variable is not capturing the data I want (inside the index class).
I'm having some trouble understanding these methods of tree traversal and how I can grab data within a table row that is not the one which contains the button that is clicked. Any advice would be appreciated, thank you.
There were a few syntax errors in your code that you need to clean up, but the issue you're having with getting the value in the index cell is that you're not going far enough up the DOM tree to run the .find() command.
$(".add").on('click', function(){
var the_name = $(this).closest("td").siblings(".name").text();
var the_type = $(this).closest("td").siblings(".type").text();
var the_index = $(this).closest("table").find("td.index").text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr style="display: none";><td class="index">index_value</td></tr>
<tr><td>section header</td></tr>
<tr>
<td class="name">Steven</td>
<td class="height">6 ft.</td>
<td><button class="add">Add</button></td>
</tr>
</table>

How to append td element in the same column of th element in a table?

I need to append data to a table dynamically from a JSON object.
After adding the titles as th elements, I am finding it difficult to add tr elements in the same column as the corresponding th element. Please help me.
{
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
}
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>
Now, I need to add items in td tags in the columns same as their corresponding th elements. like:
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
<tr>
<td>Item1</td>
</tr>
<tr>
<td>Item2</td>
</tr>
<tr>
<td>Item3</td>
</tr>
</table>
How can I do this using jQuery? (My problem is bigger than this. I simplified it so that it can be understood. Thank you!)
Here you go, Press Run code snippet and check if this works for you.
var nodes = {
"Category2":"Item2",
"Category1":"Item1",
"Category3":"Item3"
};
$(function(){
var th_elements = $('table').find('th'); // find <th> in HTML
th_elements.each(function(){ // Loop as much <th> found
var html = $.trim($(this).html()); // get HTML and compare with nodes key
$('table').append('<td>'+nodes[html]+'</td>'); // append data to table
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table>
<th>Category1</th>
<th>Category2</th>
<th>Category3</th>
</table>

Rows-Element, where are these whitespaces coming from?

First: My problem is that by inserting strings into several fields of a form from a row via DOM, the values occure with a lot of whitespaces, both at the beginning and the end.
What I want to do:
look up the values of the cells in the row I doubleclicked, and put these values in the fields of a form.
The HTML is equivalent to :
<form>
<fieldset>
<legend> Very Important </legend>
<label for="input_representing_all_the_inputs">
<input id="input_representing_all_the_inputs"></input>
</fieldset>
</form>
<table id="issue_table" class="sortable", border="1" >
<tr ondblclick="values_into_form(issue_table)">
<td>
a value
</td>
<td>
another one
<td>
</tr>
<tr ondblclick="values_into_form(issue_table)">
<td>
here's also another value
</td>
<td>
aaand one more.
</td>
</tr>
</table>
<table id="not_the_issue_table" class="sortable", border="1">
[...] blabla looks similar [...]
</table>
Now I got a js function to look up values from the table and putting them into the form.
function values_into_form( id ) {
//find index of row with given id
for (i = 0; i<= document.getElementById("accl_content").rows.lenght; i++){
if ( document.getElementById("issue_table").rows[i].id == id) {
var idx = i;
break;
}
}
// now insert the values into the editor-form
document.getElementById("input_representing_all_the_inputs" =
document.getElementById("issue_table").rows[idx].cells[0];
// repeat the above for each input_field with the specific cell_idx.
}
}
So now, let's look at the first of the first of issue_table.
The value is "a value". However, the inputfield will contain something like " a value ".
Is there a specific misstake I made to produce this?
I don't want a solution to get rid of the whitespaces, I want a real solution, want to say, I don't want them to occure at all.
I'm fresh to JS, coming from lua. So if I made some conceptional misstakes, I would be happy if you could tell me in a sidenote.
Change your html to this:
<table id="issue_table" class="sortable", border="1" >
<tr ondblclick="values_into_form(issue_table)">
<td>a value</td>
<td>another one<td>
</tr>
<tr ondblclick="values_into_form(issue_table)">
<td>here's also another value</td>
<td>aaand one more.</td>
</tr>
</table>
The spaces are because in your html there are spaces. You could of course alternatively strip beginning and ending white spaces using javascript. But if you do not want to do that, the above solution should work.
It is good practice to separate HTML and JavaScript.
JavaScript:
var myTable = document.getElementById("myTable");
var myInput = document.getElementById("myInput");
var td = myTable.getElementsByTagName("td");
for(var i = 0; i < td.length; i += 1) {
td[i].addEventListener("dblclick", function() {
myInput.value = this.innerHTML;
});
}
Demo

Categories