Basic JavaScript create table inquiry - javascript

I succeeded in creating a very basic (no 'for loops' used, I'm a beginner) table in JavaScript tagged onto an HTML button. It works perfectly!
<input type='button' value='Table' onclick='createTbl()' />
function createTbl() {
//set up elements
tbl = document.createElement('table');
tr = document.createElement('tr');
th1 = document.createElement('th');
th2 = document.createElement('th');
//contents
content1 = document.createTextNode('Last Name');
content2 = document.createTextNode('First Name');
//append
row1 = tbl.appendChild(tr);
row1.appendChild(th1).appendChild(content1);
row1.appendChild(th2).appendchild(content2);
//display
document.body.appendChild(tbl);
}
However, when I removed the enclosing function, ... :
//same code here but tagging the 'var' with each variable used
... everything disappears, leaving only the HTML button! I commented the button out, but no luck here as well.
How come? What is the magic table(t) to make it appear without enclosing it in a function?

Well, if it only works when it's within a function is because you call it from your onclick button. Otherwise the code is just there and nobody is calling it. Try calling the function when the dom has loaded to ensure everything is loaded (document.onload = createTbl)

Okay, so I partly figured out the problem: I forgot I was writing the script inside the head section of the HTML. I think that explained why the button worked flawlessly. So I moved only the code inside the function (coz I wanted it not to be a function) and placed it inside the script tag in the body section and hit refresh. At first nothing happened, until I added these:
<div id='table-div'>
<!--table here-->
</div>
script:
//display table
document.getElementById('table-div').appendChild(tbl);
And there it was! All that for a single row and two columns!
Out of curiosity, I wondered if it would work having the code back in the head section and applying my new found solutions. So with the code back in the head section, I made this slight change to display the table:
//display table
document.body.getElementById('table-div').appendChild(tbl);
No cigars here. Perhaps bad JavaScript lingo. Nevertheless, it was still good to find out that div was the magic table(t) my code needed.

Related

HTML "onclick" event in JavaScript (In a table)

I'm trying to convert a table I've written in HTML into Javascript because I want the table to be dynamically generated (# of rows). The main issue I'm having is that the individual cells in the table are clickable and open up another html page. Unfortunately, the html "onclick" parameter doesn't work with document.write statements Here is an examples of a table cell in HTML:
<td id="r1c1" align="center" onclick="getTicket(1,'plan',1);"><script language="JavaScript">document.write(getDate(1,"plan", "r1c1")); </script></td>
The functions in this line are predefined and work so I'm not going to post those, but the idea is that the function getTicket(..) is suppose to open up another html page.
My issues is how to get the onclick to work in JavaScript. I can create the cells in Javascript using document.write commands but don't really know how to make those cells clickable to run the function getTicket(..).
Your style of Javascript programming is ancient, to say the least. document.write is a function developed mainly when there were almost no common methods to generate dynamic content.
So, you should generate your elements dynamically with methods like document.createElement, append your content there, then attach the elements to the DOM with modern methods like appendChild.
Then, you can attach event listeners using something more modern than the traditional way like onclick, like addEventListener. Here's a snippet:
var td = document.createElement("td");
td.innerHTML = getDate(1, "plan", "r1c1");
td.addEventListener("click", function() {
getTicket(1, 'plan', 1);
});
row.appendChild(td);
I supposed that row is the row of the table that you're generating.
Unfortunately, IE<9 uses a different method called attachEvent, so it'd become:
td.attachEvent("onclick", function() { ...
You can modify attributes in HTML using function setAttribute(Attribute, Value).
With this function you can generate the cell code and define dinamically the attribute.
You should not use document.write to add elements to your page, there are javascript functions for this:
var myCell = document.createElement('td');
myCell.setAttribute('id', 'r1c1');
myCell.setAttribute('align', 'center');
myCell.onclick = function () {
getTicket(1, 'plan', 1);
};
// myRow is the 'tr' you want this 'td' to be a child of.
myRow.appendChild(myCell);
See it in action: http://jsfiddle.net/teH7X/1/
Can you please try below code, if that is working then let me know I will give you some better option:-
<script>
document.onload = function()
{
document.getElementById('r1c1').onclick = function()
{
getTicket(1,'plan',1);
}
}
</script>
Please check and let me know.

Append a script into a div

I've got a little problem and I'm stucking on it for a couple of days.
I downloaded a Javascriptcalendar plugin (Date Input) to add a little calendar in my form.
In this form I added a button wich add another line in this form to let user set severals dates.
<input type="button" value="Ajouter" onclick="ajoutChamp('creneau')" />
I made a little script :
var s = document.createElement('script');
s.type = "text/javascript";
s.text = "DateInput('creneau_2',true,'DD-MON-YYYY')";
$("#test").append(s);
But when I'm doing this, every time I press the button I've got my calendar who appears fullscreen. It's look like the script has been executed but no appened in the html page.
Little piece of my html code :
<table id="liste_creneau" class="add_champ">
<tr id="tr_creneau_1">
<td><label for="creneau_1">creneau 1</label></td>
<td><script id="ref_date">DateInput('creneau_1', true, 'DD-MON-YYYY')</script></td>
</tr>
</table>
<div id="test">
</div>
Atm I wanted to append the calendar in a div but at the end the calendar will be in the table.
I have done other tests too but every piece of code I made ended the same way...
So maybe you could help me! :)
Edit:
Ok I made a little test
var g = document.getElementById('test');
var s = document.getElementById('ref_date');
nb++;
var clone = s.cloneNode(true);
var param = clone.firstChild.data.split('\'');
param[1] = 'creneau_'+nb;
clone.firstChild.data = param.join('\'');
g.appendChild(clone);
After that, when I click on the button, there is a script tag inserted in the div but nothing shows up. When I inspect my html page I can see it but the calendar doesn't apear...
Bye
Edouard
I don't understand why you are not just running the date input line. It should have the same effect.
DateInput('creneau_2',true,'DD-MON-YYYY');
Regardless, you could just try and do it all in jQuery rather than mixing javascript selectors.
$("#test").append("<script type='text/javascript'>DateInput('creneau_2',true,'DD-MON-YYYY');</script>");
Well I chosen to use the jQuery-UI datepicker instead... So I guess it's solved, thanks a lot Agentminlindu and all the others :)

Alternative to jQuery replaceAll()?

I have some code that removes a tr from a dynamically built table as a jQuery object (each tr has a unique id: trid):
tri = $("#"+trid+"");
var newrow = '<tr id="newr"><td colspan="4" align="center"><div id="nrow"> </div></td></tr>';
tri.after(newrow);
tri.detach();
I then put a form in the div 'nrow' using innerHTML... There's a jQuery ui datepicker in the form that works this first time.
When the form is cancelled I put the list back to the way it was:
setTimeout("tri.replaceAll( $('#newr') )", 400);
This all works beautifully, except that it kills the jquery ui datepicker in the form if I try to edit that (or any) row after that. I've trouble shot it down to being the replaceAll line. If I take that out and replace the list by building it again it works just fine (it's not the timeout either).
So is there another way to replace the tr 'newr' with the jquery object 'tri' without using replaceAll (replaceWith doesn't work either)?
EDIT:
OK so this is how I move the form from the div elsewhere on the page:
eP = $('#eP');
eP.replaceAll( $('#nrow') );
$("#editPast").show('blind','',500,'');
eP contains the hidden div editPast...
then in the cancel function I put eP back:
setTimeout(function() {eP.appendTo($('#ePreplace')); }, 500); (thanks adeneo!)
before I tri.replaceAll, though with the setTimeout it happens after...
So I guess my problem is that eP doesn't carry the datepicker state after it's been used in #nrow, just the html.
FIXED!
changed eP.appendTo to $('#eP').appendTo so that it takes it from the dom instead of the original variable. Oops! Thanks for making me re-think this with your just detach() comment!
FIXED!
changed eP.appendTo to $('#eP').appendTo so that it takes it from the dom instead of the original variable. Oops! Thanks adeneo for making me re-think this with your 'just detach()' comment!
Thanks NiftyDude for suggesting I do this too...

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Update a tbody's html with javascript (no lib): possible?

I want to update the contents of a TBODY (not the entire TABLE, because there's much more semi-meta data (LOL) in that). I get >= 0 TR's from the server (XHR) and I want to plump those in the existing table. The fresh TR's must overwrite the existing TBODY contents.
I've made a very simple, static example on jsFiddle that works in Chrome and probably all the rest, except for IE (I only use Chrome and test in IE8).
In Chrome, the very first attempt works: plump the TR's in the TBODY. No problem!
In IE it doesn't... I've included a not working example of what I had in mind to get it working.
I'm sure this problem isn't new: how would I insert a string with TR's in an existing TBODY?
PS. jQuery doesn't have a problem with this!? It's used here on SO. jQuery does something to the HTML and then inserts it as HTML nodes..? Or something? I can't read that crazy lib. It happens in this file (look for "html: function(". That's where the magic starts.
Anybody have a function or idea for this to work without JS library?
Here is a good resource about the problems of innerHTML and IE.
The bottom line is that on tbody the innerHTML property is readonly.
Here is a solution presented in one of the comments:
var innerHTML = "<tr><td>Hello world!</td></tr>";
var div = document.createElement("DIV");
div.innerHTML = "<table>" + innerHTML + "</table>";
// Get the tr from the table in the div
var trElem = div.getElementsByTagName("TR")[0];
Regarding the jQuery part of the question:
//inside the html() function:
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
//inside the empty() function (basically removes all child nodes of the td):
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
//append calls domManip applying this to all table rows:
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
//domManip as far as I can tell creates a fragment if possible and calls the three lines above with this=each row in turn, elem=the tbody(created if missing)
Using plain JavaScript, you can set the innerHTML property of the relevant element. The text that you set can contain a mix of HTML and text. It will be parsed and added to the DOM.

Categories