JavaScript - Working With Insertbefore Method Li'l Help Please
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!!!! 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?
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); Why is the callwhy is the slice method only a method of an Array instance? The reason why I ask is because if you want to use it for the arguments property of function object, or a string, or an object, or a number instance, you are forced to use Array.prototype.slice.call(). And by doing that, you can pass in any type of object instance (Array, Number, String, Object) into it. So why not just default it as a method of all object instances built into the language? In other words, instead of doing this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; console.log(typeof arguments);//Object console.log(arguments instanceof Array);//false var args1 = Array.prototype.slice.call(arguments); console.log(args1); var args2 = Array.prototype.slice.call(obj); console.log(args2); var args3 = Array.prototype.slice.call(num); console.log(args3); var args4 = Array.prototype.slice.call(string); console.log(args4); Core('dom','event','ajax'); Why not just be able to do this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; var args = arguments.slice(0); var args2 = obj.slice(0); var args3 = num.slice(0); var args4 = string.slice(0); //right now none of the above would work but it's more convenient than using the call alternative. } Core('dom','event','ajax'); Why did the designers of the javascript scripting language make this decision? Thanks for response. I am using javascript for adding and removing rows from table as per user require ment like if we press ADDROW button it adds extra row to table and if we pressREMOVEROW it delets the last row.. Now i want to access the data from textbox like this.. var crpt = document.getElementById("itrtr2").value; //no. of rows for(var k=1;k<=crpt;k++) { qtyc = document.getElementById("txtRowc3"+k).value; unit_pricec = document.getElementById("txtRowc5"+k).value; alert('QTYC:'+qtyc+' UPC:'+unit_pricec); cttl = qtyc * unit_pricec; document.getElementById("txtRowc6"+k).value = cttl.toFixed(2); csbttl = csbttl + cttl; } document.getElementById("subttlC").value=csbttl.toFixed(2); it shows the value of textRowc3i in qtyc in alert box but also givs error document.getElementById("txtRowc3"+k) is null.. I tried for this but problem is not solved please help... Thank You... Write a public static method named starPrinter that will take an int as a parameter and print lines of stars as shown below. The header of the method will be public static void starPrinter(int n) . This is what it should look like: Please help! When you use a form and submit it the URL bar changes to what the submitted values are. So can anyone explain how to use this?
Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm Code: window.onload = initForm; function initForm() { document.getElementById("months").selectedIndex = 0; document.getElementById("months").onchange = populateDays; } function populateDays() { var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31); var monthStr = this.options[this.selectedIndex].value; if (monthStr != "") { var theMonth = parseInt(monthStr); document.getElementById("days").options.length = 0; for(var i=0; i<monthDays[theMonth]; i++) { document.getElementById("days").options[i] = new Option(i+1); } } } Thank you! I am very interested in learning this and would love any help! I am trying to impliment Javascript code to replace the MS Tabular data control. How do I go about creating a Fields collection object that has a default method of Item(idx) ie. myrs.Fields.Item(4).name is the same as myrs.Fields(4).name I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. So I'm new around here, and to web dev in general, but I've got a (hopefully) short question. I am trying to call a function (nextMonth()) every second from the time that the cycle method gets called, until it is called again. As of now I am trying to use setInterval, (and I previously tried with setTimeout and using a callback argument but maybe I wasn't doing that properly). The problem is that after running the cycle() method for 5 or 6 seconds, the entire browser freezes up and you have to kill it and restart it. Here is my code as of now: Code: function cycle() { if(CYCLEINT != null) //STOP THE CYCLE LOOP { window.clearInterval(CYCLEINT); CYCLEINT = null; document.getElementById("cycle").innerHTML = "Cycle Months"; } else //LOOP IS NOT RUNNING, INITIATE AND CONTINUE INTERVAL. { CYCLEINT = self.setInterval("nextMonth()", 1000); document.getElementById("cycle").innerHTML = "Pause"; } } function prevMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal > 1) { dVal--; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } } function nextMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal < dateMax) { dVal++; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } if(CYCLEINT != null && dVal >= dateMax) { cycle(); } } I'm trying to write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0(1) up to that maximum power, inclusive. For example, I'm trying: printPowersOfN(4, 3); printPowersOfN(5, 6); printPowersOfN(-2, 8); which should give me: 1 4 16 64 1 5 25 125 625 3125 15625 1 -2 4 -8 16 32 64 -128 256 but I only get: 64 15625 256 Here's my code: Code: public class Powers { public static int printPowersOfN (int base, int exponent) { int answer = 1; for (int i=1; i <= exponent; i++) { answer*=base; } return answer; } public static void main(String[] args) { System.out.println(printPowersOfN(4, 3)); System.out.println(printPowersOfN(5, 6)); System.out.println(printPowersOfN(-2, 8)); } } What should I change so that it does all of the powers? Have the code check that the statement has at least one character. You can do this by using the trim method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be: Statement: Response: Say something, please. Could someone help me with this? I'm not sure how to make it check to see if the user input has 0 characters. i want to write a code which would prompt the user for his first name and last name with space in between them.The full name must be entered in the same prompt box.Using the charCodeAt() method i wanna test the first character of the user's first name as well as last name.If the first character of first name is in lowercase then it should alert the user as "first name must start with uppercase".And if the first character of second name is in uppercase then it should alert the user as "second name must start with lowercase". ..plzzzz help me and give me some code for this..i m a beginner in javascript..
Sup gents. Im having problems with the link method. Its tied up to a button in the form. The link method sees the "global" variable and determines if its 1 or 0. If its 1 it gives a certain msg and if its 0 another one. Problem its always reading the variable as 0 and giving me the same message regardless of the fact that im typing the username and password correc Code: <html> <head> <script type ="text/JavaScript"> var counter = 0; var counter2 = 0; var arraynumb = 0; var arraynumb2 = 0; var global; var array = ['Mohamad', 'Karim', 'Anthony', 'Rami', 'Natalia', 'Sarah', 'Samer', 'Violette', 'Plume', 'Sharshabil']; var array2 = ["1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009"]; function pass(){ var searchKey = document.searchform.inputVal.value; for (var i = 0, len = array.length; i < len; i++){ if (array[i] == searchKey){ counter = 1; arraynumb = i; } } } function pass1(){ var searchKey2 = document.searchform.inputVal2.value; for (var i = 0, len = array2.length; i < len; i++){ if (array2[i] == searchKey2){ counter2 = 1; arraynumb2 = i; } } } function access(global) { if (counter == 1 && counter2 == 1 && arraynumb == arraynumb2) { window.alert("You may now access the website"); global = 1; } else window.alert("You may not access the website"); global = 0; } function link(global) { if (global == 1) { window.alert("you may proceed to the link"); } else window.alert("you are not signed in, please do so"); } </script> </head> <body> <form name = "searchform" action = ""> <p>Enter username<br/> <input name = "inputVal" type = "text" size = "30"/> <input name = "search2" type = "button" value = "Search" onclick = "pass()"/> </p> <p>Enter password<br/> <input name = "inputVal2" type = "password" size = "30"/> <input name = "search" type = "button" value = "Search" onclick = "pass1()"/> <input name = "Access site" type = "button" value = "Access" onclick = "access()"/> <input name = "link to" type = "button" value = "link" onclick = "link()"/> <br/> </p> <br/> <p></p> </form> </body> </html> Hi there I'm trying to figure out what the following syntax for split means in the following line of the code arrTest[0].split('/')[0] what does ('/')[0] means in split('/')[0]? please can anyone explain Hi guys For learning (regx), I'm working with the following example taken from an old resource. Example 1 is the original code and example 2 is my effort because I couldn't get example 1 to work. Any idea why example 1 doesn't work? Is the shortcut notation not valid anymore? LT Code: Example 1. In the following example, RegExp.input is set by the Change event. In the getInfo function, the exec method, called using the () shortcut notation, uses the value of RegExp.input as its argument. <script type="text/javascript"> function getInfo(){ //example 1 //doesn't work. a = /(\w+)\s(\d+)/(); alert(a[1] + ", your age is " + a[2]); } function getInfo2(info){ //example 2. works. //alert(info); re = /(\w+)\s(\d+)/; mArry = re.exec(info); alert(mArry[1] + ", your age is " + mArry[2]); } </script> </head> <body> <form> <!-- example 1 original //--> <input type="text" name="NameAge" onchange="getInfo(this);" /> <!-- example 2 //--> <input type="text" name="NameAge" onchange="getInfo2(this.value);" /> </form> I don't even know where to begin with this one. I don't know the terminology for what I am trying to do here, and the sample code is too big and cluttered to post. So I put together the following to illustrate the structure of the object that I am trying to overcome. I have a method chain within an object, and I need to override one of the methods, but when I do so I loose access to the private methods and properties of it's containing object... I googled this for several hours, and the best that I can come up with is that I need to somehow use call() to access the scope of another object. But I don't understand call() or apply() at all, and I've read many tutorials on those... Code: window.oModule['Report'] = (function(){ var _privateProp1 = '' , _privateMethod1 = function(){ // ... } , _publicMethod1 = function(){ // ... } , _publicMethod2 = (function(){ var _sub_privateProp1 = '' , _sub_privateMethod1 = function(param1,param2){ // ... } , _sub_publicMethod1 = function(){ // ... } , _sub_publicMethod2 = function(start , end){ // I need to replace this method from somewhere else var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... _neededValue += _sub_privateMethod1(arg1,arg2) } return _neededValue; } ; return{ '_sub_publicMethod1' : _sub_publicMethod1 , '_sub_publicMethod2' : _sub_publicMethod2 } })() ; return{ '_publicMethod1' : _publicMethod1 , '_publicMethod2' : _publicMethod2 } })(); alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This works fine oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; // ... return start+end } alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This will alert 6 (as intended) oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... different set of instructions _neededValue += _sub_privateMethod1(arg1,arg2) // This line causes an error: _sub_privateMethod1 is undefined } return _neededValue } You may have see various sites where urls are encoded by advertisement redirection service mostly by adf.ly now I want to write a personal java snippet for tor remove this spam [In opera you can specify a custom js to run at every page] mostly the html will look like this Code: <a target="_blank" href="http://adf.ly/246619/http://www.mediafire.com/download.php?lg5z42ra13ac9hi">SteamTable App</a> I want to use .split() method as you see this part http://adf.ly/246619/ [before the second http] has to be splitted some how & url to be reinserted in the a tag. any help here |