JavaScript - Problem Replacing Element / Doc Write From Regex
Code:
var bakaBanner; bakaBanner = document.getElementById('head'); if (bakaBanner) { var str=/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/; document.write(str.replace(/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/, "http://img218.imageshack.us/img218/5904/revyblacklagoon1.png")); } Alright, here's the deal... This is a script to be used in Greasemonkey. The page this is for changes their banner every 5 minutes, the name changes and it could be either jpg or png. I'm fairly certain my regex itself: \/images\/banners\/[A-Za-z0-9_]+.[a-z]+ Is correct... Here's an example of what it's looking through: Code: <div id="head" style="background-image: url(/images/banners/kiminitodoke.jpg);" > <div id="header_left"> <div id="rss"> My guess is that it has something to do with this line: document.write(str.replace(/\/images\/banners\/[A-Za-z0-9_]+.[a-z]+/, "http://img218.imageshack.us/img218/5904/revyblacklagoon1.png")); I'm new with Javascript, so I don't really understand why it's not working... :/ Similar TutorialsHey guys... Basically I need a function that will remove numerous elements from a page based on their class. I then also need a function to bring those elements back afterwards. If anyone is wondering, I'm trying to add buttons to remove/add images. Thanks! Ok, i have a javascript that creates a table then appends it to an empty div. This works fine in FF, however it fails to work in IE8. [edit] I have decided to post the entire code since I wasn't having any luck getting any suggestions. Maybe now someone can help me out. Code: function createTable() { var machine = document.Catalog.machine.value; var dSearch = document.Catalog.dSearch.value; var section = document.Catalog.section.value; var x = xmlDoc.getElementsByTagName('record'); var y = xmlDoc.getElementsByTagName('data'); var newEl = document.createElement('TABLE'); newEl.className = 'resultsTab'; var tmp = document.createElement('TBODY'); newEl.appendChild(tmp); var row = document.createElement('TR'); var n = 1; var headings = new Array("Col1", "Col2", "Col3", "Col4", "Col5"); var dcount = 0; //for (t=0;t<10;t++) { for (t=0;t<y[0].childNodes.length;t++) { if (y[0].childNodes[t].tagName == "record") { // it is required for FF to work properly dcount++; } } if (document.Catalog.thumbImg[0].checked) { var container = document.createElement('TH'); var theData = document.createTextNode("Pic"); container.className = "topline1"; container.appendChild(theData); row.appendChild(container); } for (h=0;h<headings.length;h++) { var container = document.createElement('TH'); var theData = document.createTextNode(headings[h]); container.className = 'topline' + n; container.appendChild(theData); row.appendChild(container); n++; } tmp.appendChild(row); switch (searchtype) { case 1: var objRegex = new RegExp(machine); break; case 2: var objRegex = new RegExp(section, "i"); break; case 3: var objRegex = new RegExp(dSearch, "i"); break; default: document.getElementById("replaceTxt").innerHTML = "<p>There was an error processing your request.</p>"; } var rowColor = 1; var noResult = "false"; for (i=0;i<dcount;i++) { var row = document.createElement('TR'); var searcharr = new Array(); for (j=0;j<x[i].childNodes.length;j++) { if (x[i].childNodes[j].nodeType != 1) continue; searcharr.push(x[i].childNodes[j].firstChild.nodeValue); } var searchstrg = searcharr.toString(); if (searchstrg.match(objRegex)) { var t; var m=1; if (document.Catalog.thumbImg[0].checked) { var pn = "images/"+searcharr[2]+".jpg"; var container = document.createElement('TD'); var refLink = document.createElement("A"); refLink.setAttribute('href', "javascript:viewImg(\""+pn+"\")"); var imgHolder = document.createElement("IMG"); imgHolder.setAttribute("src", pn); imgHolder.style.height = "75px"; refLink.appendChild(imgHolder); container.appendChild(refLink); container.className = "img"+rowColor; row.appendChild(container); } for (t=0; t<searcharr.length; t++) { container = document.createElement('TD'); var theData = document.createTextNode(searcharr[t]); container.appendChild(theData); container.className = 'line' + rowColor + '_' + m; row.appendChild(container); m++; } tmp.appendChild(row); rowColor == 1 ? rowColor++ : rowColor--; document.getElementById("replaceTxt").innerHTML = ""; document.getElementById("replaceTxt").appendChild(newEl); noResult = "true"; } } if (noResult=="false") { document.getElementById("replaceTxt").innerHTML = "<h3>Sorry, there was no match to your search. Please try again</h3>"; } } xmlDoc is the xml object from my import xml function. it is working correctly. IE does not give any JS errors, it just does nothing. If I put text in the Code: document.getElementById("replaceTxt").innerHTML field, IE displays the text in the correct spot so I know the code is working. I also verified the data is being written correctly to "newEl" via IE 8 debugger. IE just does not want to append the newEl child to the <div> tag. This is where I assume the problem is. I am using the below regex to extract the subdomain from the url Code: ^(?!www)([^.]+)\.mydomain\.com The above code extracts subdomain only when the url is typed as Quote: subdomain.mydomain.com But I need a regex which extracts sudomain when the url is typed with WWW and without WWW as below Quote: subdomain.mydomain.com www.subdomain.mydomain.com Kindly help me. Hi all, I have a string which contains HTML and *possibly* IMG tags. I am trying to extract part of each IMG tag which may be in the string. The string is part of a chat-box message which may or may not contain smilies. Here is a typical line of text, without processing (note I mis-spell the bbcode "quote" so as not to fool this board): Code: [qoute="Krupski"]<img src="./images/smilies/smile.gif" alt=":smile:" title="smile" /> <img src="./images/smilies/thumbsup.gif" alt=":thumbsup:" title="thumbsup" /> <img src="./images/smilies/thumbsdown.gif" alt=":thumbsdown:" title="thumbsdown" />[/qoute] Notice that each image has an "ALT" attribute which contains the smiley code of the smiley image. THAT is what I want to extract. This is the regex I am using to grab each smiley code: Code: txt = txt.replace(/<img(?:.*?):(.*?):(?:.*?)\/>/gi,':$1:'); The weird thing is, the regex grabs the FIRST and LAST of the three, but not the middle one! I'm sure the stupid mistake is sitting right in front of my face, but I'm not seeing it. Any help will be greatly appreciated! Thanks. -- Roger Hi all, First... this isn't homework... Now, I'm trying to make a live Regular Expression evaluator and I thought it would be really simple, but it's not working. Here's the JS I wrote..... Code: <html> <head> <style type="text/css"> body { background-color:#ddeeff; } textarea#inp1, textarea#inp2, textarea#out1 { margin:0 25%; margin-bottom:1%; border:0; padding:0; width:50%; height:100px; border: 1px solid #000000; } p { margin:0 25%; } </style> <script type="text/javascript"> function test() { var inp1 = document.getElementById('inp1'); /* regex in here */ var inp2 = document.getElementById('inp2'); /* test string here */ var out1 = document.getElementById('out1'); /* results here */ r = inp1.value.split(','); /* get find , replace */ var str = inp2.value; var find = r[0] || ''; var repl = r[1] || ''; var result = str.replace(find, repl); out1.value = result; } </script> </head> <body> <p>regex</p> <textarea id="inp1"></textarea> <p>test string</p> <textarea id="inp2"></textarea> <p>result</p> <textarea id="out1"></textarea> <script type="text/javascript"> setInterval('test()', 100); </script> </body> </html> Now, it DOES work if I do something simple like enter the word "Test" for the test string and T,X for the "regex" (the result transforms into "Xest" as it should). But if I put in something like this: /<p(.*?)>(.*?)<\/p>/gi,'$2' for the regex and <p class="test">Hello</p> for the test string The result is <p class="test">Hello</p> when it should be just Hello I can put regex strings into an array and of course it works (for example): Code: var find = [/<p>/g,/<\/p>/g]; var repl = ['P open', 'P close']; var n = find.length; while (n--) str = str.replace(find[n], repl[n]); ...blah...blah... So why doesn't my code work when I'm using variables that contain find and replace strings??? Am I missing something, or can it not be done this way? -- Roger (edit to add): The above code is online HERE document.write("<script type='text/javascript' src='http://www.website.com/javscript.js'></script>"); For some reason this will not output correctly. It ouputs "); Which is the last three characters. Hi all, I'm working on an internal site for my company and I have a snippet of code that works 100% fine indepentantly but when I try to use it inside a document.write I can't get it to work. I'm pretty sure it's down to the structure of it but I'm inexperienced with JS so I'm not sure how do correctly structure it. Here is the code I want inside of a document.write(): Code: <a href='javascript: void(0);' style="text-decoration:none; font-size:14px;" onclick=" document.getElementById('my_hidden_div_id_1').innerHTML = '<iframe src=\'{file:link}\' width=\'880\' height=\'500\'></iframe>' $('#my_hidden_div_id_1').koverlay({title: '{file:filename}'}); $('.css_koverlay').css({'background-color':'#9c183a'}); ; "> Pop-Up</a> Could anyone help me correctly insert it inside document.write() so that it outputs without errors? Thanks! Hey I'm having a problem with this line: Code: var val1 = document.sform.sel1.value; sform is the name of a form that the data is being put onto. Problem is I want to change that name to verifypage.php When I replace sform with the verifypage.php I believe (I have no clues on JS) that the . if the extension of verifypage.php is screwing the code up. It's a dynamic drop down list that I want to display the results on another page. Thanks! document.write("<table><tr><td><a href='#' onMouseOver='MM_swapImage('changeMe','','images/calNum/calNum4g.jpg',1);'><img id='changeMe' name='changeMe' src='images/calNum/calNum1.jpg' border='0'/></a></td></tr></table>"); basically the one thing I am know is a problem or at least where the problem starts is when the ","(comma) is added in the parathesis for the params of MM_swapImage. Whats the correct way to write those commas? Hello, I have a problem with the following code! I want to use it so that customers check a checkbox under each photo they want, in a photo gallery, and when they finish, they can click and the photos they checked appear using document.write in a new page! The problem I have is that when the script finds the first image, it uses document.write, shows only the first image it finds and then ends the foor loop! How can I code it so that it finds all the photos first and then shows them in the new page! Here is the sample code, sorry for my bad English and thanks for your time! -------------------------------------------------------------------------- <script type="text/javascript"> function findphotos(test){ for (i=0; i<document.test.checkgroup.length; i++){ if (document.test.checkgroup[i].checked==true){ document.write('<img src="'+i+'.jpg">'); } } } </script> <form name="test"> <input type="checkbox" name="checkgroup" /> <input type="checkbox" name="checkgroup" /> <input type="checkbox" name="checkgroup" /> </form> <h1 onclick="javascript:findphotos(test)">Find</h1> How come when the page below loads, I see the "Ahh!" but not the "HELLO??". The "Ahh!" is generated by the document.write() in JavaScript. Anytime I use it, the other HTML in the page seems to stop loading. Any thoughts? - - - - - - - <html> <head> <title>test</title> </head> <body> <script type="text/javascript"> window.onload = Scream; function Scream() { document.write("Ahh!!"); } </script> <br><br><br><br> HELLO?? </body> </html> If the value is negative it should be in red, otherwise it should be in green. It looks like JavaScript completely ignores the css class. Help please. Code: <html> <head> <title>Prva</title> <style type="text/css"> span.Pozitivno { color:green; font-weight:bold; } span.Negativno { color:red; font-weight:bold; } </style> <script type="text/javascript"> function vpisi_stevila() { var a; var b; //Vnos spremenljivk a=prompt("Vnesi stevilo a:") b=prompt("Vnesi stevilo b:") a=a*1 //S tem spremenimo string v int b=b*1 //Izpis stevil if(a<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } if(b<0) { document.write("A:<span class='Negativno'> " + a + " </span> <br />"); } else { document.write("A:<span class='Pozitivno'> " + a + " </span> <br />"); } document.write("Vsota:", a+b, "<br />"); document.write("Razlika:", a-b, "<br />"); document.write("Mnozenje:", a*b, "<br />"); document.write("Deljenje:", a/b, "<br />"); document.write("Ostanek:", a%b, "<br />"); if(a>b) //Ce je A vecje od B { document.writeln("A je <b>večje </b> od b") } if(a<b) //Ce je B vecje od A { document.writeln("A je <b>manjse </b> od b") } if(a==b) //Ce sta enaka { document.writeln("A je <b>enako </b> b") } } </script> </head> <body onload="vpisi_stevila()"> </body> </html> I have the following HTML code: Quote: <form id="registration" action="/cgi-bin/registration.cgi" method="POST" onsubmit="return control()"> <fieldset> <legend>Fill up this module</legend> Private <input id="private" type="radio" name="type" value="private" onclick="return addPrivate()"/><br/> Community/Organization <input id="organization" type="radio" name="type" onclick="alert('Organization')"/><br/> <br/> and the following javascript code: Quote: function addPrivate() { var root = document.getElementById('registration'); var label1 = document.getElementById('label'); label1.appendChild(document.createTextNode('First Name: ')); var label2 = document.getElementById('label'); label2.appendChild(document.createTextNode('Last Name: ')); var label3 = document.getElementById('label'); label3.appendChild(document.createTextNode('Address*: ')); var label4 = document.getElementById('label'); label4.appendChild(document.createTextNode('Profession: ')); var div = document.createElement('div'); div.appendChild(label1); div.appendChild(label2); div.appendChild(label3); div.appendChild(label4); root.appendChild(div); } but div tag is not added. Where is the problem? I want a mouseout event to trigger only when I leave the parent element not when I mouseover a child element. I've been using the script from quirksmode but it can be hard to get working. Code: function doSomething(e) { if (!e) var e = window.event; var tg = (window.event) ? e.srcElement : e.target; if (tg.nodeName != 'DIV') return; var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement; while (reltg != tg && reltg.nodeName != 'BODY') reltg= reltg.parentNode if (reltg== tg) return; // Mouseout took place when mouse actually left layer // Handle event } I have a function that needs to work only when the parent is moused out of. I didn't make this script. It's called by ondblclick="transition(document.getElementById('select1'),0,800,20)" in the html Code: function transition(ele,dirflag) { if((ele.dirflag == dirflag) && ele.intrans) return; // stops function being called multiple times var totDur = arguments[2] || 1000; // third argument, or one seconds var numSteps = arguments[3] || 30; // fourth argument, or thirty steps (video quality, 30fps) var intrval = totDur/numSteps; // renamed so it can't conflict ele.sopac = 0; // we start at 0 ele.shght = 50; // we start at 50px ele.eopac = 1; // we end at 1 ele.ehght = 140; // we end at 140px ele.iopac = (ele.eopac-ele.sopac)/numSteps; // how much to increment opac ele.ihght = (ele.ehght-ele.shght)/numSteps; // how much to increment hght ele.copac = parseFloat(ele.copac,10) || ele.style.opacity || ele.sopac; // a val for current ele.chght = ele.chght || parseInt(ele.style.height,10) || ele.shght; // a val for current ele.dirflag = dirflag; // changed name to dirflag, stored for reference if(ele.intrans) clearInterval(ele.intrans); // clear timeout if already running... if(dirflag) { // 1 or true = increment // alter visibility here to make an invisible item visible before starting ele.style.display='block'; ele.intrans= setInterval(function() { if(ele.copac<ele.eopac ) { // if mods needed ele.copac=parseFloat(ele.copac,10)+parseFloat(ele.iopac,10); // increment if(ele.copac>ele.eopac) ele.copac=ele.eopac; // error correction ele.chght=parseFloat(ele.chght,10)+parseFloat(ele.ihght,10); // increment if(ele.chght>ele.ehght) ele.chght=ele.ehght; // error correction // set styles accordingly ele.style.opacity = ele.copac; ele.style.filter = 'alpha(opacity='+parseInt(ele.copac*100,10)+')'; ele.style.height = ele.chght+'px'; } else { clearInterval(ele.intrans); // we're done -- clear timeout } },intrval); // do it on intrval timeline } else { // 0 or false = decrement ele.intrans= setInterval(function() { if(ele.copac>ele.sopac || ele.chght>ele.shght) { // if mods needed ele.copac=parseFloat(ele.copac,10)-parseFloat(ele.iopac,10); // decrement if(ele.copac<ele.sopac) ele.copac=ele.sopac; // error correction ele.chght=parseFloat(ele.chght,10)-parseFloat(ele.ihght,10); // decrement if(ele.chght<ele.shght) ele.chght=ele.shght; // error correction // set styles accordingly ele.style.opacity = ele.copac; ele.style.MozOpacity = ele.copac; ele.style.KhtmlOpacity = ele.copac; ele.style.filter = 'alpha(opacity='+parseInt(ele.copac*100,10)+')'; ele.style.height = ele.chght+'px'; } else { clearInterval(ele.intrans); // we're done -- clear timeout // and make the item disappear here since it's done transitioning. ele.style.display='none'; } },intrval); // do it on intrval timeline } } // all done! I tried to do this: Code: function transition(ele,dirflag,e){ if (!e) var e = window.event; var tg = (window.event) ? e.srcElement : e.target; if (tg.nodeName != 'DIV') return; var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement; while (reltg != tg && reltg.nodeName != 'BODY') reltg= reltg.parentNode if (reltg== tg) return; // Mouseout took place when mouse actually left layer // Handle event if((ele.dirflag == dirflag) && ele.intrans) return; // stops function being called multiple times var totDur = arguments[2] || 1000; // third argument, or one seconds var numSteps = arguments[3] || 30; // fourth argument, or thirty steps (video quality, 30fps) var intrval = totDur/numSteps; // renamed so it can't conflict ele.sopac = 0; // we start at 0 ele.shght = 50; // we start at 50px ele.eopac = 1; // we end at 1 ele.ehght = 140; // we end at 140px ele.iopac = (ele.eopac-ele.sopac)/numSteps; // how much to increment ........ With this in the html onmouseout="transition(document.getElementById('select1'),1,800,20,event) but it doesn't work. the event isn't getting passed to the function. i have tried to move the event before document.getElementById and put e before ele in the function but it still doesn't work. Nothing fires at all. I've just added the quirksmode script to other functions in the past and had them work. I know this won't be the last time I need to stop problems with mouseover so can you give me some tips on what is going wrong. and please no script librarys. Hi, im new to Js and i have this code: Code: var div = document.createElement("div"); div.id = field+count; div.name = field+count; div.class = "bubble_green"; var p = document.createElement("p"); p.appendChild(document.createTextNode('Question '+count)); div.appendChild(p); field_area.appendChild(div); assuming that the variables are all correct and working, why is only this produced: Code: <div id="question_3"><p>Question 3</p></div> instead of: Code: <div id="question_3" name="question_3" class="bubble_green"><p>Question 3</p></div> and is there a solution? I am trying to make images change as the user selects the option from the dropdown menu , I have called alert("test1"); alert("test2"); to check if the functions are being called but only the first one happens, can you please tell me what's wrong with the script. Here is the script:
Code: var oImageChooser; addEvent( window, "load", initialize) function initialize() { alert("test1"); var oImageChooser = document.getElementById("imageChooser"); addEvent(oImageChooser, "change", loadCached); } var imageLibrary = new Array(); imageLibrary["image1"] = new Image(120,90); imageLibrary["image1"].src = "images/desk1.gif"; imageLibrary["image2"] = new Image(120,90); imageLibrary["image2"].src = "images/desk2.gif"; imageLibrary["image3"] = new Image(120,90); imageLibrary["image3"].src = "images/desk3.gif"; imageLibrary["image4"] = new Image(120,90); imageLibrary["image4"].src = "images/desk4.gif"; function loadCached() { alert("test2"); var imgChoice = oImageChooser.options[oImageChooser.selectedIndex].value; document.getElementById("thumbnail").src = imageLibrary[imgChoice].src; } here is the html Code: <html> <head><title>Image dropdown</title> <script type = "text/javascript" src = "experimento5.js"> </script> </head> <body onload = "initialize()"> <h1> Choose any image</h1> <img id = "thumbnail" src = "images/desk1.gif" > <form> <select id = "imageChooser"> <option value = "image1"> Bands</option> <option value = "image2"> Clips</option> <option value = "image3"> Lamp</option> <option value = "image4"> Erasers</option> </select> </form> </body> </html> Code: function offPar(){ alert(this.offsetParent.id); } function init(){ var mine = document.getElementById("mid"); var other = document.getElementById("inner"); mine.addEventListener("click", offPar, false); other.addEventlistener("click", offPar, false); } window.addEventListener('load', init, false); HTML : <div id = "content"> <div id = "mid"> <div id = "inner"> <p class = "par"> </p> </div> </div> </div> I can add an event listener to the #mid div but I can't to the #inner div. Anyone now why this is? Sorry I can't provide more info. That's all I Know! TTFN John Hello I am fairly new to Javascript. I have a function which takes a string which consists of key value pairs and sets a form control based on key being the form element name and value being the value to set. eg string could be "key1=orange;key2=2;key3=whetever" Here is the function: function processresponse(frm, serverResponse) { var items = serverResponse.split(";"); for(var i = 0; i < items.length; i++) { var item = items[i]; var eqchar = item.search("="); if(eqchar != -1) { var key = item.slice(0, eqchar); var value = item.slice(eqchar+1); var elemname = key; if(document.getElementById(elemname) != null) { var type = frm.elements[elemname].type; if (type=="checkbox") { value == "1" ? frm.elements[elemname].checked=true : frm.elements[elemname].checked=false; } else if (type=="text"){ //do processing for text (text input) frm.elements[elemname].value = value; } else if(type=="select-one"){ //only one is openformmode - default to [0] - true if(value == "0" || value.length == 0) { frm.elements[elemname].options[0].selected = true; } else { frm.elements[elemname].options[1].selected = true; } } else { alert("unknown ctrl type: " + type + " name: " + frm.elements[elemname].name + " val: " + value + " key: " + key); } } //if(frm.getElementById(elemname) } } } The problem line is: var type = frm.elements[elemname].type; elemname is case sensitive so if for example the form element is called dog and the string elemname is Dog, then the line fails with Error: 'elements[...].type' is null or not an object So my check if(document.getElementById(elemname) != null) is insufficient to guard against this. I realise I could do a try catch but there must be a more legant way than that. How can I test the formname more reliably? Any ideas would be very welcome. Angus |