checking table rows in Javascript - javascript

I'm using this JS function to dynamically add labels to a table, this function is called from a combo box selection index change, when user selects a new item, it should be added to label, I'm going to check current values of table (i.e. rows of table) and only add the new item if it is new, what should I do? how can I check existing items (labels) of table?
var spanTag = document.createElement("span");
spanTag.id = document.getElementById('cmbDestinationUser').selectedIndex.toString();
var e = document.getElementById("cmbDestinationUser");
var strUser = e.options[e.selectedIndex].text;
spanTag.innerHTML = strUser;
var TR = document.createElement('tr');
var TD = document.createElement('td');
TD.appendChild(spanTag);
TR.appendChild(TD);
document.getElementById('tblReceivers').appendChild(TR);
thanks

You're adding a span with a fixed id - you can just find if it already exists:
if( document.getElementById( spanTag.id ) == null )
{
// add it
}
Also, you could simplify your life amazingly with a bit of jQuery. I think this is equivalent to what you're trying to do :
id = $('#cmdDestinationUser').val();
if( $("#"+id).length == 0 )
{
selText = $('#cmdDestinationUser option:selected').val();
$("#tblReceivers").append("<tr><td><span id='" + id + "'>" + selText + "</span></td></tr>");
}

Related

How do I get the row and column values when a button is pressed in a HTML table?

I'm looking to have it so when the user clicks on one of the "Get Sequence" buttons, it calls a function, which is shared among all "Get Sequence" buttons, that passes in the values specific to that row and col.
For example, if the user were to click on the rad51/mouse "Get Sequence" button, the function would pass in "rad51" and "mouse". HTML
What I have thus far:
function createTable(){
//call firebase
var genes = ["rad51", "dmc1"];
var genomes = ["human", "mouse", "dog"];
var geneCount = genes.length;
var genomeCount = genomes.length;
var table = document.getElementById("inventory");
var firstRow = document.getElementById("firstRow");
var x = 0;
var y = 0;
while(x < geneCount){
var data = document.createElement('td');
var text = document.createTextNode(genes[x]);
data.appendChild(text);
firstRow.appendChild(data);
x++;
}
while(y < genomeCount){
//create new row
var newRow = document.createElement('tr');
var data = document.createElement('td');
var text = document.createTextNode(genomes[y]);
data.appendChild(text);
newRow.appendChild(data);
x = 0;
while(x < genes.length){
var currentGene = genes[x];
var currentGenome = genomes[y];
data = document.createElement('td');
data.setAttribute("id", currentGene);
var getSequenceButton = document.createElement("button");
text = document.createTextNode("Get Sequence");
getSequenceButton.appendChild(text);
???----> getSequenceButton.addEventListener("click", getId(this.parent));
var changeColorButton = document.createElement("button");
data.appendChild(getSequenceButton);
data.appendChild(changeColorButton);
newRow.appendChild(data);
x++;
}
table.appendChild(newRow);
y++;
}
};
I fixed my own problem. So what I did was assign an id to each of the buttons to the information that I was interested in. The function assigned to each button passed in the event object where I could then parse for the id with event.target.id
I think this could be a possible solution using Jquery, assuming your table doesn't change its structure:
$(document).ready(function(){
$(".table_button").click(function(){
//alert(this.innerHTML);
var rowValue = $(this).parent().children().first().text();
var columnValue = $("th").eq($(this).parent().find(this).index()).text();
//alert($(this).parent().find(this).index());
alert("RowValue: " + rowValue + "\n" + "ColumnValue: " + columnValue);
});
});
https://jsfiddle.net/ow1naqvL/
Basically i get the first <td> of the relative <tr> of the button row (to get "human" and so on). Then, i use the button index for get the text of <th> at that index.
Pure Javascript solution could be a little bit tricky.
Hope it helps

Adding a new row to html table on click event

I have a list with names, each name has a sublist with subitems.
I need to pass those subitems to the table when I click on the name.
Here is an example, try to expand the first name.
But if I click on it again, it will keep adding that value to different cells of the table. How may I add this only once ? Or always at the same place?
Also, I have some attributes of the disciplines:
data-time = The time the discipline start;
data-id = The ID of that discipline (all brought from database);
My Code:
/*JQuery*/
$(document).ready(function(){
$(".prof-list h3").click(function(event){
var obj = event.target;
var disciplina_id = $(this).next().find('li').data('id');
var disciplina_hora = $(this).next().find('li').data('time');
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
else if(disciplina_hora == "08:30:00"){
var myRow = document.getElementById("prof-table").rows[1];
myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
}
if(obj.nodeName == "H3")
$(this).next().slideToggle();//Aplica efeito slide
//$("#list_prof").html("clicked: " + event.target.nodeName ); //Teste
})
})
use .cells[] to update cell content
if(disciplina_hora == "14:30:00"){
var myRow = document.getElementById("prof-table").rows[3];
// insert if `myRow` only has 1 cell
if(myRow.cells.length <= 1)
myRow.insertCell(1);
// use `cells[1]` to update the 2nd cell content
myRow.cells[1].innerHTML = $(this).next().find('li').text();
}
Edit Update
if(myRow.cells.length <= 1){
$(this).next().find('li').each(function(idx, elm) {
myRow.insertCell(idx + 1);
myRow.cells[idx + 1].innerHTML = $(elm).text();
});
} else {
while(myRow.cells.length > 1)
myRow.deleteCell(1);
}

Read td values by tr id from the same table

I am trying to read the values of table based on the tr id, but cannot wrap my head around how to do this.
// Id of the tr in question for example.row_17
var d =c["id"];
console.log(d);
// Here I can read all the td values, but I only want
// the ones inside the tr id = "row_17"
var cols =document.getElementById('report_table').getElementsByTagName('td'),
colslen = cols.length, i = -1; > while(++i < colslen)
{ console.log(cols[i].innerHTML);
}
Since you tagged it with jQuery, you can do it by doing something like this:
var id = c["id"];
// Select only the row with id specified in 'id' and loop through all 'td's' of that row.
$("#" + id).find("td").each(function()
{
// Log the html content of each 'td'.
console.log($(this).html());
});
Just in case you want a solution for JavaScript only (no jQuery):
var id = c["id"];
var tds = document.querySelectorAll('#' + id + ' td');
for(var i = 0; i < tds.length; i++) {
console.log(tds[i].innerHTML);
}
Demo

jQuery loop through table to display values

I'm at a loss here.
I created a quick script that will add a new row to a table and also has the capability to delete a row.
jsFiddle -->http://jsfiddle.net/wLpJr/10/
What I want to achieve is this:
Display each value of each row (in the div with id='thedata')
I originally started off with adding a number at the end of each id, starting at '1', and incrementing each time the user adds a row.
//This is random code
var rowcount = parseInt($('#rowcount').val());
var newcount = rowcount + (1*1);
var x = $('#radioinput' + newcount).val('a value');
$('#rowcount').val(newcount);
The problem is that lets say you add 5 rows. Now delete row 3. When you loop through the table of data you will get an error because row "3" does not exist. You have rows 1, 2, 4, 5, 6. Specifically - the input with id = 'radioinput3' will not be present.
I then decided to do this:
$('#maintable > tbody > tr').each(function() {
radiovalue[i] = $("input[type='hidden']", this).map(function() {
var vid = 'radio' + i;
var myval = this.value;
var radioinput = document.createElement("input");
radioinput.type = "hidden";
radioinput.value = myval; // set the CSS class
radioinput.id = vid;
$('#maintable').append(radioinput);
}).get()
text1value[i] = $('td > input', this).map(function() {
var vid = 'text1pos' + i;
var myval = this.value;
var text1input = document.createElement('input');
text1input.type='hidden';
text1input.value = myval;
text1input.id = vid;
$('#maintable').append(text1input);
}).get()
text2value[i] = $('td > input', this).map(function() {
var vid = 'text2pos' + i;
var myval = this.value;
var text2input = document.createElement('input');
text2input.type='hidden';
text2input.value = myval;
text2input.id = vid;
$('#maintable').append(text2input);
}).get();
});
The problem here is that I'm getting 'undefined' values.
You are looping through a counter, which you increment everytime you add a new row, but do not take into account that a row can be deleted at any time. Instead, just use the each function to loop over the elements remaining in the DOM.
Add thead and tbody tags to your table, it will make your life easier.
I'm not sure why you have those hidden div to hold the input[type=radio] values, you don;t need them, access the values directly.
$('#showdata').click(function() {
$("#maintable tbody tr").each(function(i, v) {
var myp = "<p>Radio value is = " + $(this).find('input[type=radio]:checked').val()
+ "\nText1 value is = " + $(this).find('input[id$=text1]').val()
+ "\nText2 value is = " + $(this).find('input[id$=text2]').val() + "</p>";
$('#thedata').append(myp);
});
});
jsFiddle Demo
You could add a CSS class to the input text fields to make it easier to get, but i just used the jQuery ends with selector.
Also, you delete selector if far too high up the DOM tree on (document), instead restrict it as near as you can, in this case the #maintable.

Add new Row before first row in java script

Hi I have code as follows:
function addRowToTable(num){
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// cell
var cell0 = row.insertCell(0);
var LNInpT = document.createElement('input');
LNInpT.setAttribute('type', 'text');
LNInpT.setAttribute('value', 'name');
cell0.appendChild(LNInpT);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInp, cbEl, raEl);
}}
Please help me to Add new Row before first row in table with editing this code.
tanks
This should help you:
var myTable = document.getElementById('myTable');
var tbody = myTable.tbodies[0];
var tr = tbody.insertRow(-1); // puts it at the start
var td = document.createElement('td');
td.innerHTML = "Something";
tr.appendChild(td);
I'd recommend you use jQuery which will make this much easier (with the prepend method). If you can't or don't want to, you should be able to use insertBefore.
You might want to look at this question on SO.
Use jQuery's prepend() method for that.

Categories