Making a rows value to be anothers text with jquery - javascript

I have a table with 2 rows, the first has an input for quantity and the following has to output that same value. Since I'm using jQuery this is my code:
var i, quant;
for (i = 0; i < $(".qnt").length; i++){
$(".qnt:eq(" + i + ")").keyup(function(){
quant = $(this).val();
console.log($(this));
console.log(i);
console.log($(".cst:eq(" + i + ")"));
$(".cst:eq(" + i + ")").text(quant);
});
}
And the sample for the rows is :
<tr>
<td><input class="qnt"/></td><td class="cst"></td>
</tr>
The jsfiddle is : http://jsfiddle.net/qrhJ4/
Question : why is the .cst selector not working and how do I make it work?

You are over-complicating things, try something like:
$('.qnt').keyup(function() {
$(this).parent().next('.cst').text(this.value);
});
http://jsfiddle.net/aasqW/

Related

How do I add an image before text to a table item which needs to be found by class?

JS:
function add(){
while(i < $('.tabledata').length){
var current_val = $('.tabledata').eq(i).text();
arr.push(current_val);
$('.tabledata').eq(i).text() = "<img src='/flags/'" + (flagsarr[current_val].toLowerCase() + '.png') + ' width="20px" style="margin-bottom: 2px;"><b>' + current_val + '</b>';
i++;
}
}
$(document).ready(function(){ add(); });
current_val is a Country. flagsarr[curren_val] is the country code: eg ES (Spain).
in this case, i want to add 'es.png' before the text 'Spain' in the table.
I tried using text() but I realised it was a function.
Please note: there are around 200 rows in the table, each with 5 pieces of data (so 5 columns), the first being the Country. Each of the first column items share the class 'tabledata'.
How can I fix this?
You can use each to iterate over tabledata and html() instead of text() to get its content:
function add() {
var $tableData = $('.tableData');
$.each($tableData, function(index, value){
var current_val = $(value).html();
arr.push(current_val);
$(value).html("<img src='/flags/'" + flagsarr[current_val].toLowerCase() + ".png'" + ' width="20px" style="margin-bottom: 2px;"><b>' + current_val + '</b>');
});
}
$(document).ready(function(){ add(); });

How to get id of a element in all the rows of a table using jQuery

My table id is "termTable". I am iterating through each row of the table. The id of textbox is "label'+ i +'" since I used for loop to generate ids randomly. The values of i will be unordered maybe after adding the rows or deleting the rows. Example: IDs are label1, label2, label3. After deleting the 2nd row, I am adding another row. So now the IDs are label1,label3, label4. I want to retrieve all the ids of all the textbox elements. How can I achieve it? Please help.
for (var i = 0; i < firstTabLength; i++) {
var row = $("#termTable tr").eq(i);
var id = row.find('input[type="text"]').attr('id'); // I could see id = undefined
}
This is Html. This is for adding the new rows to table. Guess you can visualize the table structure with the help of below code.
function AddCustomTerm1() {
len = len + 1;
var table = document.getElementById("termTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" class="form-control" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
row.insertCell(1).innerHTML = '<select class="form-control" id="dataTypes' + (len - 1) + '" name="dataTypes' + (len - 1) + '" onchange="changeDataType(this)"></select>'
row.insertCell(2).innerHTML = '<input type="text" class="form-control" id="ContractTerm' + (len - 1) + '" name="ContractTerm' + (len - 1) + '" value="">';
var DD = document.getElementById("dataTypes" + (len - 1));
for (var i = 0; i < datatypesarray.length; i++) {
var opt = document.createElement("option");
opt.text = datatypesarray[i];
opt.value = datatypesarray[i];
DD.appendChild(opt);
}
without you html format cant help much.
but try this ones.you dont even need a for loop to get all the textbox and their ids from table.
var ids=[];
$('#termTable input[type="text"]').each(function(){
ids.push($(this).attr('id'))
})
if you want ids of the textboxes in first column of the table.the try this
var ids=[];
$('#termTable tr').each(function(){
ids.push($(this).find('td:first-child input[type="text"]').attr('id'))
})
The best practice is to add a specific class to all of your elements that need to be iterated.
For example add the class term-table-input to your inputs:
row.insertCell(0).innerHTML = '<input type="text" class="form-control term-table-input" id="label' + (len - 1) + '" name="label' + (len - 1) + '" value=""><input type="hidden" id="step' + (len - 1) + '" value="1"/>';
And iterate them with:
var termTableInputIDs = [];
$('.term-table-input').each(function () {
termTableInputIDs.push($(this).attr('id'));
});
Also you could read more about writing efficient css here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
Since you have more than one input[type="text"] in a row, you should take the first. Also you can use each() instead of for.
$('#termTable tr').each(function() {
var id = $(this).find('input[type="text"]:first').attr('id');
console.log(id);
});
You find all the input elements inside the table by using $('#termTable input') and to loop through all the selected elements you use $.each API
Use Code like below.
var InputIds = []; //array to hold your id's
$.each($('#termTabel input[type="text"]'),function(i,v){
InputIds.push($(this).attr('id'));
});
console.log(InputIds.toString());
//this finds all inputs which id start from "label"
$('#termTable input[id^="label"]').each(function(){ console.log(this.id); });
example: https://jsbin.com/lisuratere/edit?html,js,output

After deletion changing id of textbox inside cell id not working

I have table using Javascript and I am deleting the rows using a delete function
After the deletion I am trying to reindex the table cell ids
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++){
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
}
}
But the following lines not working:
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
<td>'s contains input boxes, it will be like this
<td><input type="text" title="notes"></td>
<td><input type="text" title="amount"></td>
How can I change the id of text box inside <td> or cell ?
I made a jsfiddle here https://jsfiddle.net/an87ka5p/
I updated this to answer the question in the comments
function test() {
var table = document.getElementById("ordertable");
var rowcountAfterDelete = table.rows.length;
for (var i = 0; i < rowcountAfterDelete; i++) {
table.rows[i].id = "row_" + i;
table.rows[i].cells[0].innerHTML = i + "<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].getElementsByTagName("input")[0].id = "notes_" + i;
table.rows[i].cells[2].getElementsByTagName("input")[0].id = "amount_" + i;
}
}

Create Rows in a Table using Javascript - adds too many cells...>

I'm trying to create a table on the fly... it almost works but I have an issue with the number of cell it adds.
My table has 8 columns (monday to Friday plus a total column at the end).
Here is the fiddle for it: http://jsfiddle.net/kaf9qmh0/
As you can see, on row 1, it adds the 8 columns 3 times, then on row 2 it adds the columns twice and only on the last row does it only add 8 columns.
I suspect it is because Im using .append to add the rows as follows (line 105 in the fiddle) but my Javascript being very limited, Im not entirely sure how to make it stop add the columns to row 1 and 2.
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex2 + '"></tr>');
How can I make it to only add the cells (td) to the next row when it loops through rowIndex2 and increments it?
Can somebody point me in the right direction please?
You had a loop within a loop - which was causing the additional cells. Here's an updated fiddle; and here's an extract of the modified code:
function createSampleRows() {
var sourceTable = document.getElementById('activityTable');
var sourceTableRows = sourceTable.rows.length;
var targetTable = document.getElementById('timesheetTable');
var rowindex;
var targetTableColCount;
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
if (rowIndex == 1) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
}
for (rowIndex = 0; rowIndex < (parseInt(sourceTableRows)-2); rowIndex++) {
var sourceTableRowID = document.getElementsByClassName('activityTaskRow')[rowIndex].id;
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex + '"></tr>');
};
// This loop was nested within the above loop
for (x = 0; x < targetTableColCount; x++) {
$("#timesheetTable > tbody > tr").append('<td id="' + x + '" style="width: 60px;height: 34px;" class=""></td>');
};
};

How to find empty tr in table using Javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to find Empty tr in table, is there any way to find it?
after finding empty row I want to insert some data in it.
Supposing you have this HTML :
<table id=tbl>
<tr><td>A</td><td>B</td></tr>
<tr><td>A</td><td>B</td></tr>
<tr><td></td><td></td></tr> <!-- this line is empty -->
<tr><td>A</td><td>B</td></tr>
</table>
Then you can fill the empty line like this :
var rows = document.getElementById('tbl').rows;
for (var i=0; i<rows.length; i++) {
var txt = rows[i].textContent || rows[i].innerText;
if (txt.trim()==="") rows[i].innerHTML="<td>Something</td>";
}
Demonstration
This uses :
the rows property of the table
textContent (or innerText for IE) to get the content without the tags
As this also use the trim function which isn't available in IE8, you might want to add this shim :
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
There might be better ways, this is what occurred to me.
$('tr').each(function() {
if($(this).find('td').length == 0) {
// empty tr
// id of tr is available through this.id
}
});
Maybe something like this $('table tr:empty').html('....')
var tables = document.getElementsByTagName('table');
var table = tables[0];
var trs = table.getElementsByTagName('tr');
for (var i = 0; i < trs.length; i++) {
if (trs[i].innerHTML === '') {
console.log('EMPTY', trs[i]);
} else {
console.log('NOT EMPTY', trs[i]);
}
}
I think its not easy. You can see this link.
HTML:
<table id="table" style="border: 1px solid green;"><tbody>
<tr id="empty"></tr>
<tr id="withText"><font style="color: red;">text</font></tr>
<tr id="withEmptyTd"><td></td></tr>
<tr id="withTdWithText"><td>text</td></tr>
</tbody></table>
<div id="output"></div>
Javascript:
var output = document.getElementById('output');
var table = document.getElementById('table');
var trs = table.querySelectorAll('tr');
var tr, id, text, tds, j, td, tdText;
for (var i = 0; i < trs.length; i++) {
tr = trs[i];
id = tr.id;
output.innerHTML += "Getting tr[" + id + "]<br />";
text = tr.innerHTML;
output.innerHTML += "tr[" + id + "].innerHTML = \"" + text + "\" it's length = " + text.length + "<br />";
tds = tr.querySelectorAll('td');
output.innerHTML += "tr[" + id + "] have " + tds.length + " tds<br />";
for (j = 0; j < tds.length; j++) {
td = tds[j];
tdText = td.innerHTML;
output.innerHTML += "tr[" + id + "] -> td[" + j + "].innerHTML = \"" + tdText + "\" its length = " + tdText.length + "<br />";
}
}
And output will be:
Getting tr[empty]
tr[empty].innerHTML = "" it's length = 0
tr[empty] have 0 tds
Getting tr[withText]
tr[withText].innerHTML = "" it's length = 0
tr[withText] have 0 tds
Getting tr[withEmptyTd]
tr[withEmptyTd].innerHTML = "" it's length = 9
tr[withEmptyTd] have 1 tds
tr[withEmptyTd] -> td[0].innerHTML = "" its length = 0
Getting tr[withTdWithText]
tr[withTdWithText].innerHTML = "text" it's length = 13
tr[withTdWithText] have 1 tds
tr[withTdWithText] -> td[0].innerHTML = "text" its length = 4
Cause any tag or text in tr but not in td shows before the table.

Categories

Resources