JavaScript - Correct Placement Of Code Using Insertbefore/after
I'm brand new to JavaScript, and I come from a purely logical scripting background so forgive me if this is the most poorly formed code/bad technique that you've recently seen.
I've played the google games for days and I surrender. I usually find a way to fight through it and figure it out, but I'm going to have to cede this one. I'm simply trying to put a new tab next to a tab that is already present on a page (classed: mirrortab_first) I'm trying to use XPath to select the element and then place newTab before it. Seemed simple enough to start. But as the code sits, the tab always winds up at the bottom of the page. Any thoughts? Kind regards. Code: var newTab = document.createElement("div"); newTab.setAttribute('id','newTab'); newTab.innerHTML = '<table cellpadding="0" cellspacing="0" border="0"><tbody><tr>' + '<td class="mirrortab_first"> </td>' + '<td class="mirrortab_back">' + '<a style="cursor:pointer;">Hide Classifieds</a>' + '</td>' + '<td class="mirrortab_last"> </td>' + '</tr></tbody></table></div>'; var tabLocation = document.evaluate('//td[contains(@class, "mirrortab_first")][1]',document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null); for (i=0; i<tabLocation.snapshotLength; i++) { tL = tabLocation.snapshotItem(i).parentNode; } document.body.insertBefore(newTab, document.tL); Similar TutorialsSo here is what I have so far. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>TableDOM</title> <script type="text/javascript"> //Appends a new row to the tea table function addTeaGrade(s){ var tableElem, trElem, tdElem, textElem //get a handle for the table tableElem = document.getElementsByTagName("table")[0] //create text element with text entered by user textElem = document.createTextNode(s) //alert(textElem.nodeValue) //create td element tdElem = document.createElement("td") //create tr element trElem = document.createElement("tr") //assemble row: //footbone connected to the ankle bone, //ankle bone connected to the shin bone, etc. tdElem.appendChild(textElem) trElem.appendChild(tdElem) //get a handle for the TBODY element var tbodyElem = document.getElementsByTagName('tbody')[0] //appendChild() inserts the new row below the header of the table. //tbodyElem.appendChild(trElem) //this here replaces the new row at the bottom of the element tbodyElem.insertBefore(trElem, tbodyElem.getElementById("hdr-row")) } </script> </head> <body> <h3>Example: Dynamic HTML Table</h3> Demonstrates how to add table elements using the DOM API. <br /><br /> <table border="1"> <tr id="hdr-row"> <th> <a href="http://www.2basnob.com/grading-tea.html">Grades of tea</a> </th> </tr> <tr id="row-1"> <td> Golden Flowery Orange Pekoe </td> </tr> <tr id="row-2"> <td> Tippy Golden Flowery Orange Pekoe </td> </tr> </table> <br /> <form style="width:650px" id="teaForm" action=""> Grade of tea to add to table: <br /> <input id="gradeBox" size="34" type="text" value="" /> <br /> <input type="button" value="Add" onclick="addTeaGrade(this.form.gradeBox.value)" /> <input type="reset" /> </form> <hr /> <h3>Drilling Down Through the DOM (w/X-Ray Vision)</h3> <script type="text/javascript"> document.write('<ol>') var elemTbl = document.getElementsByTagName('table')[0].firstChild document.write('<p>Children of table element:</p>') while (elemTbl) { document.write('<li>' + elemTbl.nodeName + '</li>') elemTbl = elemTbl.nextSibling } var elemTBODY = document.getElementsByTagName('TBODY')[0].firstChild document.write('<p>Children of TBODY element:</p>') while (elemTBODY) { document.write('<li>' + elemTBODY.nodeName + '</li>') elemTBODY = elemTBODY.nextSibling } var el = document.getElementById('hdr-row').nextSibling; document.write('<p>Siblings of hdr-row:</p>') while (el) { document.write('<li>' + el.nodeName + '</li>') el = el.nextSibling } document.write('</ol>'); </script> <hr /> <h3>The Complex Table Model</h3> The Complex model incorporates all the elements of Simple tables in addition to many new elements that give the author even more organizational control. The Complex model gives the developer the ability to group Table Rows into THEAD, TBODY and TFOOT sections. <br /><br /> The TBODY element is part of a trio of table grouping elements that organize a series of Table Rows [TR] into Header [THEAD], Body [TBODY] and Footer [TFOOT] sections. <br /><br /> The THEAD and TFOOT section markers are optional, but one or more TBODY sections are always required. <br /> <br /> To allow for backward compatibility with the older Simple Table Model, if no TBODY structures exist in a table, the entire set of row groupings [TR] are assumed to be a single TBODY. </body> </html> I don't see what I am doing wrong I assume it is referencing the wrong nodes? Any help would be great. I try to insert a list item into an Ul,it works fine except in IE. PHP Code: var menu_name = document.getElementById("main").value; var real_pos = document.getElementById("main_pos").value; var menu_pos = real_pos-1; var ul = document.getElementById("vert_menu"); var li = document.createElement("li"); li.setAttribute("name","list"); li.innerHTML = "<a href='#nogo'>" + menu_name + "</a>"; line36-----> ul.insertBefore(li,document.getElementsByName("list")[menu_pos]); Jslint says the code is valid. IE says:invalid argument line 36,character6. I'm working on a greasemonkey script that requires me to append a tag before each instance of a tag with a specific class name. It works when there's no parent tags but when it goes into levels deep it doesn't work. So how can I use insertbefore?
Hello everyone, I'm working with the insertBefore method and am having a slight issue that l'm sure is very easy to fix but l can't figure it out. If you look at the following page and click the "add game" button you'll see that extra "game" tables are added to the page. http://www1.theworldlink.com/test/insertBefore.php In the above example the <div id="box_scores"></div> tag is found directly before the closing <body> tag (and l need it inside of a form element). however on this example: http://www1.theworldlink.com/test/insertBefore2.php I have the <div id="box_scores"></div> div inside of a form element as apposed to directly before the closing <body> tag and the script fails to work. Here is the JS code that l'm using: Code: newDiv = document.createElement("div"); newDiv.innerHTML = 'test test test'; my_div = document.getElementById("box_scores"); document.body.insertBefore(newDiv, my_div); and l'm certain the problem is he document.body.insertBefore(newDiv, my_div); I've tried: document.body.forms[0].insertBefore(newDiv, my_div); and several other varients but l can't figure it out.... any help would be greatly appreciated!!!! I want the inserted text to be under the droplist not on top of it! <html> <body> <script type="text/javascript"> function showSelected(val) { document.getElementById('selectedResult').innerHTML="<a href='mailto:" + val + "'>" + val + "</a><p><font size=3></font> </p>" } </script> <div id='selectedResult'></div> <!-- This sets up the drop down list of names --> <select name='test' onChange='showSelected(this.value)' ID=Select1> <option value='user.1@email.net'>First User</option> <option value='user.2@email.net'>Second User</option> </select> </body> </html> Hi, Would you please try the following in IE: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <style type="text/css"> * { font-family: Verdana; font-size: 96%; } label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> <script> $(document).ready(function(){ $("#curl").focus(function(){ if( this.value == this.defaultValue ) { $(this).val("http://"); } }); $("#commentForm").validate(); }); </script> </head> <body> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>A simple comment form with submit validation and default messages</legend> <p> <input id="cname" name="name" size="25" class="required" value="Name" /> </p> <p> <input id="cemail" name="email" size="25" class="required email" value="Email" /> </p> <p> <input id="curl" name="url" size="25" class="url" value="URL" /> </p> <p> <textarea id="ccomment" name="comment" cols="22" class="required">Comment</textarea> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form> </body> </html> As you see the cursor goes back to the beginning of the field if you focus on the URL field. It works with no problem in other browsers. How can it be corrected? Thanks for any help! hello i am trying to include the following following in my code, but it keeps creating an error. i need to know the correct place to include the function.many thanks Code: CODE ---------------------------------------- <script type="text/javascript"> $(function() { $("#flex1").flexigrid( { url: 'staff.php', dataType: 'json', colModel : [ {display: 'ID', name : 'id_con', width : 40, sortable : true, align: 'left'}, {display: 'Name', name : 'name_con', width : 150, sortable : true, align: 'left'}, {display: 'Email', name : 'email_con', width : 150, sortable : true, align: 'left'}, {display: 'Phone', name : 'phone_con', width : 250, sortable : true, align: 'left'}, {display: 'Mobile', name : 'mobile_con', width : 150, sortable : true, align: 'left'}, {display: 'Fax', name : 'fax_con', width : 150, sortable : true, align: 'left'}, {display: 'Notes', name : 'notes_con', width : 250, sortable : true, align: 'left'} ], buttons : [ {name: 'Edit', bclass: 'edit', onpress : doCommand}, {name: 'Delete', bclass: 'delete', onpress : doCommand}, {separator: true} ], searchitems : [ {display: 'Name', name : 'name_con'}, {display: 'Email', name : 'email_con', isdefault: true}, {display: 'Position', name : 'position'} ], sortname: "name_con", sortorder: "asc", usepager: true, title: "Staff", useRp: true, rp: 10, showTableToggleBtn: false, resizable: false, autowidth: true, autoheight: true, singleSelect: true } ); }); FUNCTION ----------------------------------------------------------- function doCommand(com, grid) { if (com == 'Edit') { $('.trSelected', grid).each(function() { var id_con = $(this).attr('id_con'); id_con = id_con.substring(id_con.lastIndexOf('row')+3); alert("Edit row " + id_con); }); } else if (com == 'Delete') { $('.trSelected', grid).each(function() { var id_con = $(this).attr('id_con'); id_con = id_con.substring(id_con.lastIndexOf('row')+3); alert("Delete row " + id_con); Does anyone know why I am not getting an alert on an empty form INPUT value? Code: if (document.forms["form"]["targetname"].value == "" && document.forms["form"]["unknownname"] == false) { alert ("What ever"); return false; } document.forms["form"]["targetname"] is a form INPUT text document.forms["form"]["unknownname"] is a form INPUT checkbox I suspect the problem is due to 'false'.. but I can't figure out why. Can anyone tell me what I have done wrong here? I have the following html code Code: <div id='group1'> <tr class='time'> <td colspan='3' name='1262815200'></td> </tr> <tr> <td class='timeleft group1' name='1262815200' colspan='3'></td> </tr> <tr class='game'> <td><input type='radio' name='G1' value='NYJ'>NYJ</td> <td><input type='radio' name='G1' value='BUF'>BUF</td> <td><select name='G1P' class='points' tabindex = '1'></select></td> </tr> </div> and when I use the selector $('#group1 input) it does not select anything (namely the inputs in this code). But when I use the selector $('div input') it will select them (and more on the page which I don't want). Is anyone able to see what I have done wrong? I've tried everything I can think of in terms of testing, and I have narrowed it down to the selector. Thanks. How can I change the day when the user select a month? When they select Feb ->29 days, select May -> 31 days. Like what facebook does. Hi there, I am new in web development. I think this problem is related to javascript. My javascript script is below which changes images after 2 sec. But when i call my start function in img tag in my third row div of my layout, it does not show images in that div or in that area. It show that series of images in first row. <script> var images = new Array ("img/1.jpg", "img/2.jpg", "img/3.jpg"); var currentIndex = 0; function Start() { setInterval("ChangeImage()", 2000); } function ChangeImage() { currentIndex++; if(currentIndex == images.length) { currentIndex = 0; } document.images[0].src = images[currentIndex]; } </script> first div in html: <div id="menu"> <img src="header/menu.png" name="menu" id="m"/> </div> My slideshow images places here, u can see i have call Start() function in another div. 3rd div html: <div id="slideshow-img"> <img src="img/3.jpg" name="myimg" id="myimg" onclick="Start()"/> </div> Please resolve my problem within an hour, I'll highly appreciate. Sorry for grammer mistakes, my english is not so good. Hi there, I am new in web development. I think this problem is related to javascript. My javascript script is below which changes images after 2 sec. But when i call my start function in img tag in my third row div of my layout, it does not show images in that div or in that area. It show that series of images in first row. Code: <script> var images = new Array ("img/1.jpg", "img/2.jpg", "img/3.jpg"); var currentIndex = 0; function Start() { setInterval("ChangeImage()", 2000); } function ChangeImage() { currentIndex++; if(currentIndex == images.length) { currentIndex = 0; } document.images[0].src = images[currentIndex]; } </script> first div in html: Code: <div id="menu"> <img src="header/menu.png" name="menu" id="m"/> </div> My slideshow images places here, u can see i have call Start() function in another div. 3rd div html: Code: <div id="slideshow-img"> <img src="img/3.jpg" name="myimg" id="myimg" onclick="Start()"/> </div> Please resolve my problem within an hour, I'll highly appreciate. Sorry for grammer mistakes, my english is not so good. I have tried many ways to do this and have also searched the forum, no go. I was doing it manually doing this: Code: Math.round((#)*100)/100 But no go, so I found this function here on the forum: Code: function roundNumber(num, dec) { var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); return result; } No go, it works yes, don't get me wrong. But I am working on a invoicing system and it needs to be exact. For instance with this number: Quote: 0.27470000001 It returns 0.27, when in reality it should return 0.28 because of the 7 changes the 4 to 5 and then 5 changes the 7 to 8. But it doesn't work. While reading some things I found while searching google I see that Math.round doesn't work 100% the way it should mathematically. So what options do I have left, I can't believe that a simple rounding calculationg that excel can do ha ha JS cannot. Which of these is the correct way to set the className attribute, or are they both okay? option 1: Code: var t = document.createElement("p"); t.className = "myclass"; option 2: Code: var t = document.createElement("p"); t.setAttribute("class","myclass"); Hello coding forum users, I am working on the only javascript chapter of my HTML textbook. It asks me to: Quote: replace the line <img id="sky" src="sky0.jpg" alt=""/> with a script element that writes the following HTML code: <img id='sky' src='mapNum.jpg' alt=' ' /> where mapNum is the value of the mapNum variable. so I try PHP Code: <script type="text/javascript" /> document.write("<img id='sky' src='mapNum.jpg' alt=' ' />") </script> after a few other attempts I search codingforums and find: PHP Code: document.write("<img id=\"sky\" src='sky"+mapNum+".jpg' alt='' />"); and PHP Code: document.write('<img id="sky" src="sky'+mapNum+'.jpg" alt="" />'); and these work perfectly fine but I don't understand why? my textbook only has one javascript chapter and its really small and vague, and my teacher hasn't answered my emails, so I would be grateful if anyone can tell my why my first code falls flat. I found and am using the following script to add checkbox values to a textarea. Code: <script type="text/javascript"> function add_sub(el){ if (el.checked) el.form.elements['type'].value+=el.value; else{ var re=new RegExp('(.*)'+el.value+'(.*)$'); el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2'); } } </script> </head> <body> <form name="form1" method=post> <textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"> </textarea><br> <input type="checkbox" name="bob" id="bob" value="<p>" onclick="add_sub(this);"><label for="bob"><p></label><br> <input type="checkbox" name="bob1" id="bob1" value="<span>" onclick="add_sub(this);"><label for="bob1"><span></label><br> <input type="checkbox" name="bob2" id="bob2" value="<div>" onclick="add_sub(this);"><label for="bob2"><div></label> That is working. However, I wanted to put carriage returns after each checkbox value added, so I added the + "\r\n" as follows: Code: <script type="text/javascript"> function add_sub(el){ if (el.checked) el.form.elements['type'].value+=el.value + "\r\n"; else{ var re=new RegExp('(.*)'+el.value+'(.*)$'); el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2'); } } </script> That is working when adding the value, but removing the value when the checkbox is unchecked is not working. I know the regular expression, etc. needs to be updated to account for the carriage returns, but I have tried everything I can think of and cannot get it to work. Help correcting the code is appreciated. Hi, I'm trying to figure out how to make this work and I'm stumped. I wrote this code: <script type=text/javascript> function firstfunction(); { if(document.form1.inputnumbers.value="55"); { document.form1.outputstate.value="this is a number"; } else if { document.form1.inputnumbers.value="never"; } { document.form1.outputstate.value="this is a number"; } else { document.form1.outputstate.value=""; } </script> <form name="form1" method="post"> <input type="text" id="inputnumbers" name="inputnumbers";> <input type="button"; value="Enter"; onclick="firstfunction()"><br><br> <textarea id="outputstate"; name="outputstate"; cols=60; rows=10; style="border:1"; readonly;> I'm trying to doing something really simple but I can't seem to make it work. I'm trying have the textarea display a certain message depending on if the first input box says a certain word or number. So like in the code, if the user types "55" or "never" in the first box, then the second box should say a certain message. Then I used the else statement so that if "55" or "never" is not entered, then the second box says nothing. If you can spot my error or suggest a different way of going about writing the code, it would be very much appreciated. Thank you. Hi there. I have a table which I would like to be highlighted with the click of a button, but I can't seem to reference it correctly. I can make the <td> clickable and function, but when I try to apply it to the button I can't make it reference the td cell, rather than change the background color of the button. The function is: function roll(obj){ obj.style.backgroundColor == "pink" ? obj.style.backgroundColor = "#e5e5e5" : obj.style.backgroundColor = "pink"; } Html: <td style="background-color:#e5e5e5;"><img onmousedown="roll(this);" src="images/plus.png" title="Highlight Lot" /></td> Thanks a lot!! :) Good evening. I'm very new to this, but very excited that I've gotten this code so close. I am trying to get the computer to determine if a number is even or not. This is what I have: [CODE] <script type = "text/javascript"> <!-- var firstNumber; // first string entered by user var answer; // the division problem // read in first number from user as a string firstNumber = window.prompt("Enter an integer"); //how to get a remainder var answer = firstNumber / 2 if (answer > 1) { document.writeln(answer + ". This number is even."); } </script> The bottom part is the problem. I am able to code that if the answer is greater than one, then return the following text, however, I can't for the life of me figure how to say... if the remainder is zero. Thank you, i am making a simple multiple choice quiz and if user gets all correct i need it to automatically go to a new page rather than having a manual button for that so they cant move on until all questons are answered correctly. Most reatful for anyhelp!!!!!! Thanks Code: <SCRIPT Language ="JavaScript"> function ValidateForm(){ result = new Array(); count = 0; if (!document.forms[0].one[3].checked == true) { result[count] = "Question 1. The correct answer is " + document.forms[0].one[3].value + "."; count++; } if (!document.forms[0].two[0].checked == true) { result[count] = "Question 2. The correct anwser is " + document.forms[0].two[0].value + "."; count++; } if (!document.forms[0].three[3].checked == true) { result[count] = "Question 3. The correct answer is " + document.forms[0].three[3].value + "."; count++; } if (!document.forms[0].four[3].checked == true) { result[count] = "Question 4. The correct answer is " + document.forms[0].four[3].value + "."; count++; } if (result.length > 0) { var vString = ""; for (var i=0; i<result.length; i++) { vString = vString + result[i] + "\n"; } alert(result.length + " incorrect answers:\n" + vString); return(false); } else { alert("All of the questions were answered correctly."); return(true); } } function MM_goToURL() { //v3.0 var i, args=MM_goToURL.arguments; document.MM_returnValue = false; for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'"); } </SCRIPT> |