I do apologize for the title, I wasn't sure what to call this. Anyways I am currently working on a WYSIWYG site builder and I've run into a little problem.
I created the following code to automatically make a 'div' appear above the selected cell for some buttons to be contained within it. The 'div' needs to disappear when a user clicks on another cell or when the user clicks on another bit of the document, etc. But I've been unable to figure out a good method of getting rid of it, would be lovely to have some help. Thank you, and also if it isn't too much to ask. I've been attempting to figure out a way for the document to automatically detect what table index is selected from where the user has their cursor. That can be seen on line 1.
http://jsfiddle.net/fwZTc/102/
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 0; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
var cellIndex = this.cellIndex;
var rowIndex = this.parentNode.rowIndex;
alert("cell: " + cellIndex + " / row: " + rowIndex );
//var div = document.createElement('div');
//div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
//div.style.color = 'red';
// better to use CSS though - just set class
//div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
//document.appendChild(div);
awesome = table.rows[rowIndex].cells[cellIndex];
awesome.innerHTML = '<div style="width:200px; height:20px; position:absolute; margin-top:-20px; background-color:#666">'
}
}
Try this instead.
HTML:
<table>
<tbody id="myTblBody">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
JQuery:
$('#myTblBody tr td').click(function(){
var html = $(this).html();
$('#box').remove();
$(this).html(html + '<div id="box" style="width:50px; height:20px; position:absolute; margin-top:-20px; background-color:#666">');
//If you would like to know row and col number.
var row = $(this).parent().index();
var col = $(this).index();
alert('row ==' + row + "col == "+ col);
});
JSFiddle
Related
Never mind. This was my mistake. This code works fine.
I have a function that's supposed to create and populate a table. I'm also trying to set the id element of some of the columns, but the function that I have isn't working and I can't seem to figure out why.
This is my code:
HTML:
<div id="result_table">
<table border="0" cellspacing="3" cellpadding="3" id="summaryTable" class="tablesorter table table-striped">
<thead>
<tr style="font-weight: bold; text-align: center;">
<th>Well ID</th>
<th>Dominant Gene</th>
<th>%</th>
<th>Secondary Gene</th>
<th>%</th>
<th>No. of Reads that Mapped</th>
<th>No. of Mutations</th>
<th>Mutation Information</th>
<th>View</th>
</tr>
</thead>
<tbody id="summaryBody">
</tbody>
</table>
</div>
Javascript:
function structureTable(test){
if (kiloseqResult==null){
throw "Error: no databse defined"
};
document.getElementById("summaryTable").style.visibility="visible";
kiloseqDatabase = JSON.parse(kiloseqResult);
var table = document.getElementById("summaryBody");
for (i=0;i<kiloseqDatabase.length;i++){
var row = table.insertRow(i);
var kiloseqKeys = Object.keys(kiloseqDatabase[i])
var keyLength = Object.keys(kiloseqDatabase[i]).length;
// Painstakingly setting up the cells...
var cell = row.insertCell(0);
cell.innerHTML = kiloseqDatabase[i]['id']
var cell = row.insertCell(1);
cell.innerHTML = kiloseqDatabase[i]['gene1'].substr(5)
var cell = row.insertCell(2);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent1']).toFixed(2)
var cell = row.insertCell(3);
if (kiloseqDatabase[i]['gene2']=="None"){
cell.innerHTML = "None"
} else {
cell.innerHTML = kiloseqDatabase[i]['gene2'].substr(5)
}
var cell = row.insertCell(4);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent2']).toFixed(2)
var cell = row.insertCell(5);
cell.innerHTML = kiloseqDatabase[i]['count']
var cell = row.insertCell(6);
cell.innerHTML = ""
var cell = row.insertCell(7);
cell.innerHTML = ""
var cell = row.insertCell(8);
cell.innerHTML = ""
};
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
};
kiloseqResult is a variable that checks whether kiloseqDatabase is populated. kiloseqDatabase contains the information that's supposed to populate the table.
Oddly enough, the for-loop that sets up the ID (and yes, I did try including this in the first for-loop but tried breaking it up when that didn't work) is fine when I run it in my Chrome's console. But it doesn't seem to work within the function.
Any help would be much appreciated. Thank you!
Have you tried putting your ID assignment logic within the document.ready scope? You can't assign an ID to an element or select it from the DOM before it's rendered:
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
}
);
Playing with a quick concept. Hopefully the answer is pretty simple, my attempt is just failing here for some reason.
Let's say I have an array such as:
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
And I'm trying to flip the data around, so it converts it into:
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
This much is completed. Now, with my new multidimensional array, I want to push each internal array's contents to an HTML table row:
<tr>
<td>1</td>
<td>4</td>
<td>7</td>
<td>10</td>
</tr>
<tr>
<td>...
Play here: http://jsfiddle.net/XDFd2/
I tried doing it with two for-loops, but it doesn't seem to be appending the <tr> or </tr>.
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');
for(var i=0; i<items_converted.length; i++){
if(i==0){
table.append('<tr>');
}
for(var j=0; j<items_converted[i].length; j++){
table.append('<td>'+items_converted[i][j]+'</td>');
if(j===items_converted[0].length-1){
table.append('</tr');
}
}
}
I feel I'm missing something very simple here... perhaps the order that the loops are processing?
Any help is appreciated.
Play here: http://jsfiddle.net/XDFd2/
You're trying to use append() like document.write(). That's a wrong approach. You should look at the DOM starting at your table node and append nodes for each row and cell.
Basically a $('<tr>') to create a row, followed by an table.append() call to add it to the DOM. Likewise for the cells.
var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
var items_converted = [[1,4,7,10],[2,5,8,11],[3,6,9,12]];
var table = $('#table');
var row, cell;
for(var i=0; i<items_converted.length; i++){
row = $( '<tr />' );
table.append( row );
for(var j=0; j<items_converted[i].length; j++){
cell = $('<td>'+items_converted[i][j]+'</td>')
row.append( cell );
}
}
Fiddle
Using JavaScript in Greasemonkey, I'm attempting to pull individual cells and read the innerHTML of each cell to search for a given string.
There's a table of 3x3, and I want to search them in the order of the center first, then depending on situation, move to not-necessarily linear progression (i.e. top-left, top, left, top-right, bottom-left, right, bottom, bottom-right).
I've put each of the cells into an array, and using splice(), I assign the cell to a variable. For testing purposes, I throw up 2 alerts with the cell variable itself, then the cell innerHTML.
When I just use the variable, the alert says [object HTMLTableCellElement], but the innerHTML is undefined.
I've created a mock page to show my example. here's the code (Also at jsBin).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4<br>
center
</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</table>
<script language="JavaScript">
var tables = document.getElementsByTagName("table");
tables[0].style.border = "thin solid red";
tables[0].id = "grid";
var grid = tables[0];
var cells = new Array();
cells[0] = grid.rows[0].cells[0]; // nw
cells[1] = grid.rows[0].cells[1]; // n
cells[2] = grid.rows[0].cells[2]; // ne
cells[3] = grid.rows[1].cells[0]; // w
cells[4] = grid.rows[1].cells[1]; // c
cells[5] = grid.rows[1].cells[2]; // e
cells[6] = grid.rows[2].cells[0]; // sw
cells[7] = grid.rows[2].cells[1]; // s
cells[8] = grid.rows[2].cells[2]; // se
var grid_string = "";
function HumanCount(cell) {
var human_regex = /Human/;
var humans = cell.innerHTML.split(human_regex);
var humans_length = humans.length - 1;
return humans_length;
}
for (a = 0; a < 9; a++) {
cells[a].count = HumanCount(cells[a]);
grid_string += cells[a].count + " ";
if (a == 2 || a == 5) {
grid_string += "<br>";
}
}
var direction = 0; // nw
var center = cells.splice(4, 1);
alert("center: " + center);
alert("innerHTML: " + center.innerHTML);
</script>
</body>
</html>
center is not an element, so it has no innerHTML property.
center is an array of elements, so if you use:
alert ("innerHTML: " + center[0].innerHTML);
you'll see what you expect.
~~~
That alert alert("center: "+center); is misleading, as it shows <td> the same as [<td>].
For more accurate (and less annoying) debugging don't use alert(). Use console.log, EG: console.log ("center: ", center); -- which would show the array as different from the element and doesn't throw up a modal dialog.
I have a dynamic form that is generated based on javascript. Here's the relevant javascript:
function addRowToTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// right cell
var cellRight = row.insertCell(0);
var el = document.createElement('textarea');
el.rows = '2';
el.cols = '80';
el.name = 'conventionSkill' + iteration;
el.size = 40;
var el2 = document.createElement('input');
el2.type = 'hidden';
el2.name = 'conventioni_alt';
el2.value = iteration;
el2.size = 40;
el.onkeypress = keyPressTest;
cellRight.appendChild(el);
cellRight.appendChild(el2);
}
function removeRowFromTable()
{
var tbl = document.getElementById('convention');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
HTML:
<table id="convention">
<tr>
<td><label>Skill Descriptions:</label></td>
</tr>
<tr>
<td>
<textarea name='convention_54' rows='2' cols='80'>
text
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(54);'><font size=
'+1'>-</font></a></td>
</tr>
<tr>
<td>
<textarea name='convention_55' rows='2' cols='80'>
text2
</textarea></td>
<td><a href='javascript:void(0)' onclick='removeRowFromTable(55);'><font size=
'+1'>-</font></a></td>
<td><a href='javascript:void(0)' onclick='addRowToTable();'><font size=
'+1'>+</font></a></td>
</tr>
</table>
I like the add function as it simply adds a new textarea. However, the remove button removes from the bottom of the form up. How can I make it so that removeRowFromTable removes a specific textarea? For example, if I want to delete one of the textareas in the middle, rather than the last one in the form.
Thanks for any suggestions!
In short, you'll have to find the exact textarea you want to remove (probably by ID).
However, before you go too far down this road hand-rolling ID enumeration and DOM manipulation code, you might want to look at jQuery (http://jquery.com/). jQuery handles oodles of this stuff quite easily via its selector mechanism and will save you from many of the cross-browser headaches you may have if you try to do all this DOM manipulation yourself.
You'll find a lot of questions about jQuery on SO; for example look at how easy this related- and-simple table manipulation is:
What is the best way to remove a table row with jQuery?
IMHO learning jQuery was a tremendous Javascript productivity boosts for me and my team -- it's well worth the time spent in my experience.
I have built a web based WYSIWYG editor, which Im accessing programatically from my cocoa application. At the moment I'm able to run scripts and retrieve the HTML from the iFrame in the editor, but I'm unable to send text from an NSTextView to the iFrame. Any ideas?
The editor is here http://www.alexmillsdesign.com/Developer/FernEngine/
Cheers
Alex Mills
I'm not an expert in this area but I have written sample code in the past that did something similar to this. The approach I took was the following: in your Cocoa class where you want to update the text insert code similar to
WebScriptObject *webScriptObject = [_webView windowScriptObject];
id result = [webScriptObject callWebScriptMethod:#"setTableRows" withArguments:[NSArray arrayWithObject:fauxData]];
where fauxData is whatever you want to pass to JS, and in the JS source have something similar to
var mytable = document.getElementById("myTable");
var mytbody = document.getElementById("myTbody");
var docFragment = document.createDocumentFragment();
var myNewtbody = document.createElement("tbody");
myNewtbody.id = "myTbody";
var trElem, tdElem, txtNode;
for(var j = 0; j < row_data.length; ++j) {
trElem = document.createElement("tr");
trElem.className = "tr" + (j%2);
tdElem = document.createElement("td");
tdElem.className = "col0";
txtNode = document.createTextNode(row_data[j].lastName);
tdElem.appendChild(txtNode);
trElem.appendChild(tdElem);
tdElem = document.createElement("td");
tdElem.className = "col4";
txtNode = document.createTextNode(row_data[j].firstName);
tdElem.appendChild(txtNode);
trElem.appendChild(tdElem);
docFragment.appendChild(trElem);
}
myNewtbody.appendChild(docFragment);
mytable.replaceChild(myNewtbody, mytbody);
and of course your HTML should have something like
<table id="myTable">
<thead id="myThead">
<tr>
<th>Last</th>
<th>First</th>
</tr>
</thead>
<tbody id="myTbody">
</tbody>
</table>
Obviously this fills in rows of data in a table, but updating text would be similar.