JavaScript - Displaying Elements By Tag Name
Hi,
I am trying to display some xml elements that are formatted like this: Code: <line> <route> <dirs>1. Head west on Calzada Roosevelt</dirs> <time>4.6 km - about 15 mins</time> <dirs>2. Continue on Carretera Interamericana/Pan American Hwy</dirs> <time>15 km - about 12 mins</time> <dirs>3. Look for turnoff at San Lucas and follow signs from there</dirs> <time>13.5 km - about 15 mins</time> </route> </line> using this js: Code: for (var a = 0; a < lines.length; a++) { routeInfo = lines[a].getElementsByTagName("route"); for (var p = 0; p < routeInfo.length; p++) { var time = GXml.value(routeInfo[p].getElementsByTagName("time")[0]); var dirs = GXml.value(routeInfo[p].getElementsByTagName("dirs")[0]); way+='<b>'+dirs+'</b>'+'<br>'+time+'<br>'; ("way" eventually gets passed as the text to display) Which works OK (as you can see here if you select from Guatemala City to Antigua), but the problem is that it only shows the first set of directions, ie Code: <dirs>1. Head west on Calzada Roosevelt</dirs> <time>4.6 km - about 15 mins</time> I can see that this is because of the [0] in the getElementsByTagName - if I change it to 1 or 2 it shows the 2nd or 3rd set of directions. But I want it to show all of them... and I thought that being in a loop it would, but I'm obviously missing something. Any ideas? Thanks in advance. Similar TutorialsAhoy, Lemme try to explain this as best as I can. Bullet points might help: When someone clicks on an image here (http://gta.kwivia.co.uk/gta-iv/), the rest of the images collapse and become invisible Below the image, some links appear Also, there will be a "show other images" button which will then show the rest of the images http://gta.kwivia.co.uk/gta-iv/ I will appreciate all solutions to this problem. If you need to know anything, simply ask me. Ok so I have these Input boxes and select boxes on my form. I have them input this way: Code: <input type="text" name="monto[]"> So I can then parse the many that get added and removed when I submit the form, this way PHP see's them as an array. Now I have used this in the past to cycle through my inputs to check values and such on them, but with these [] it doesn't work. Code: var changeCheck = document.getElementsByName('check'); for(i=0; i<changeCheck.length; i++) { var enter = new Number(getEl('dueitem' + changeCheck[i].value)); if(changeCheck[i].checked == true) { final = enter + final; } } Is there a way to cycle all these elements when they are as []. Even if it's cycle them by name, though I never had a determined amount I always have the same names for the 12 different fields there are. Hi all, iv'e been trying to get round this for 2 days and still nothing. What i want to do is to be able to outline elements on a page when hovered over... simple you might think. which it is. Then with the id of the item outlined when right clicked, and chose an option, other things happen. The menu side is sorted, and the hover outline is sorted. But iv'e been trying to put them both together but it wont work! This is the closest iv'e gotten, whcih runs sooooo slow. Code: $(document).ready(function() { function elementHover(){ $("*").bind("mouseover", function(event) { var element = $(event.target); if($(element).attr("rel")!="rightClickMenu"){ $(element).addClass('outline-element'); if( ($(element).attr("id")!="") && (typeof $(element).attr("id") != "undefined") ){ getElementObj($(element)); $("[id!='" + $(element).attr("id") + "']").hover(function(){ $("#" + $(element).attr("id")).removeClass('outline-element'); }); }else{ return ""; } }else{ return ""; } }); } elementHover(); }); the big problem being this var element = $(event.target); if i changed it to var element = $(event.target); alert($(element).attr("id")); it would open the dialog box about 10 times spitting all kinds of results. Any help would be much appreciated. Hi, I got a table with hundreds of rows...and I want the user to be able to hide a single one by clicking on the table row. How can I do this without typing in hundreds of ids like 1,2,3,4,5... Since you can't get elements by class and ids have to unique I'm not sure how to do this. Also the order of the rows will change when they get updated so it would end up being a mess of unordered ids. Thanks. I put this at the end of my code thinking that after the div displays (id = 'link_container') I can eliminate (id = 'link_container') from memory when the script ends so there's a place for another div (id = 'link_container') when/if there's onkeyup event. Wouldn't this little script remove any element with an id = 'link_container' ? <script type="text/javascript"> var deleteDiv = document.getElementById('link_container'); document.body.removeChild(deleteDiv); </script> What am I doing wrong here. I'm trying to generate this code into my listOfSquares UL using javascript: Code: <a href="#" id="square0"><li class="square"></li></a> This is my complete code: Code: <html"> <head> <title>Squares</title> <style> li.square { width: 26px; height: 26px; border: 1px solid black; display: block; float: left; margin: 5px; background-color: #39F; } div#squares { width: 725px; margin: 50px; background-color: #CCC; float: left; } div#form { width: 700px; text-align: center; clear: both; margin: 50px 50px 0 50px; } </style> <script> <!-- function generateSquare() { var number = 0; var squareID = "square" + number; var container = document.getElementById('listOfSquares'); var linked = document.createElement('a'); linked.setAttribute('href', '#'); linked.setAttribute('id', squareID); container.insertBefore(linked, container.firstChild); addToElement(squareID); } function addToElement(elementID){ var new_element = document.createElement('li'); new_element.setAttribute('class', 'square'); document.getElementById(elementID).innerHTML=new_element; } //--> </script> </head> <div id="form"> <form> <input type="button" value="Generate Square" onclick="generateSquare()" /> </form> </div> <body> <div id="squares"> <ul id="listOfSquares"> </ul> </div> </body> </html> Im working on a function where i need to return the active elements ID. the element will have class="main" id="1" onmouseover="showSub()"> Would someone be able to write me a simple function which simply puts the elements ID number in an alert box? I can figure out the rest i need from that . Thanks, Tom I have a webpage which has the prototype library in it as well as my own script. I just started on it, but I've already run into issues using the for... in loop. I'll admit, I'm a complete noob at javascript, so this is probably something pretty simple. Code: function prepareToolBar() { //define toolbar tool names var toolbar = [ 'line', 'circle', 'ellipse', 'square', 'rectangle', 'text']; for (var i in toolbar) { var tmp = document.createElement("p"); tmp.appendChild(document.createTextNode(toolbar[i])); document.body.appendChild(tmp); } } addLoadEvent(prepareToolBar); function addLoadEvent(func) { var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } Below is the output on the page from the function: Code: circle ellipse square rectangle text function (iterator, context) { var index = 0; iterator = iterator.bind(context); try { this._each(function (value) {iterator(value, index++);}); } catch (e) { if (e != $break) { throw e; } } return this; } function (number, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var index = - number, slices = [], array = this.toArray(); while ((index += number) < array.length) { slices.push(array.slice(index, index + number)); } return slices.collect(iterator, context); } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = true; this.each(function (value, index) {result = result && !!iterator(value, index);if (!result) {throw $break;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result = false; this.each(function (value, index) {if ((result = !!iterator(value, index))) {throw $break;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; this.each(function (value, index) {results.push(iterator(value, index));}); return results; } function (iterator, context) { iterator = iterator.bind(context); var result; this.each(function (value, index) {if (iterator(value, index)) {result = value;throw $break;}}); return result; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (iterator(value, index)) {results.push(value);}}); return results; } function (filter, iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var results = []; if (Object.isString(filter)) { filter = new RegExp(filter); } this.each(function (value, index) {if (filter.match(value)) {results.push(iterator(value, index));}}); return results; } function (object) { if (Object.isFunction(this.indexOf)) { if (this.indexOf(object) != -1) { return true; } } var found = false; this.each(function (value) {if (value == object) {found = true;throw $break;}}); return found; } function (number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; return this.eachSlice(number, function (slice) {while (slice.length < number) {slice.push(fillWith);}return slice;}); } function (memo, iterator, context) { iterator = iterator.bind(context); this.each(function (value, index) {memo = iterator(memo, value, index);}); return memo; } function (method) { var args = $A(arguments).slice(1); return this.map(function (value) {return value[method].apply(value, args);}); } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function (value, index) {value = iterator(value, index);if (result == null || value >= result) {result = value;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var result; this.each(function (value, index) {value = iterator(value, index);if (result == null || value < result) {result = value;}}); return result; } function (iterator, context) { iterator = iterator ? iterator.bind(context) : Prototype.K; var trues = [], falses = []; this.each(function (value, index) {(iterator(value, index) ? trues : falses).push(value);}); return [trues, falses]; } function (property) { var results = []; this.each(function (value) {results.push(value[property]);}); return results; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (!iterator(value, index)) {results.push(value);}}); return results; } function (iterator, context) { iterator = iterator.bind(context); return this.map(function (value, index) {return {value: value, criteria: iterator(value, index)};}).sort(function (left, right) {var a = left.criteria, b = right.criteria;return a < b ? -1 : a > b ? 1 : 0;}).pluck("value"); } function () { return [].concat(this); } function () { var iterator = Prototype.K, args = $A(arguments); if (Object.isFunction(args.last())) { iterator = args.pop(); } var collections = [this].concat(args).map($A); return this.map(function (value, index) {return iterator(collections.pluck(index));}); } function () { return this.length; } function () { return "[" + this.map(Object.inspect).join(", ") + "]"; } function (iterator, context) { iterator = iterator.bind(context); var result; this.each(function (value, index) {if (iterator(value, index)) {result = value;throw $break;}}); return result; } function (iterator, context) { iterator = iterator.bind(context); var results = []; this.each(function (value, index) {if (iterator(value, index)) {results.push(value);}}); return results; } function (object) { if (Object.isFunction(this.indexOf)) { if (this.indexOf(object) != -1) { return true; } } var found = false; this.each(function (value) {if (value == object) {found = true;throw $break;}}); return found; } function () { return this.map(); } function reverse() { [native code] } function forEach() { [native code] } function () { this.length = 0; return this; } function () { return this[0]; } function () { return this[this.length - 1]; } function () { return this.select(function (value) {return value != null;}); } function () { return this.inject([], function (array, value) {return array.concat(Object.isArray(value) ? value.flatten() : [value]);}); } function () { var values = $A(arguments); return this.select(function (value) {return !values.include(value);}); } function (sorted) { return this.inject([], function (array, value, index) {if (0 == index || (sorted ? array.last() != value : !array.include(value))) {array.push(value);}return array;}); } function (array) { return this.uniq().findAll(function (item) {return array.detect(function (value) {return item === value;});}); } function () { return [].concat(this); } function () { var results = []; this.each(function (object) {var value = Object.toJSON(object);if (!Object.isUndefined(value)) {results.push(value);}}); return "[" + results.join(", ") + "]"; } As you can see, it shows the 6 elements in the array that I want, but it also shows random elements. By the way, I can fix this by changing it to a normal for loop, but I want to know what I'm doing wrong. Hi I wanted to create multiple check box and once check box is clicked user should able to enter text and submit so i created this but when check box toggle it keep creating text areas. i wanted to create 1 text area per one check box also i need to store each text area value to data base. how can i correct this to achieve my needs PHP Code: <script type="text/javascript"> function validate(chk){ if (chk.checked == 1){ var htmlText = "<textarea name='area' cols='40' rows='5'></textarea>"; var newElement = document.createElement('div'); newElement.id = 'text'; newElement.innerHTML = htmlText; var fieldsArea = document.getElementById('text'); fieldsArea.appendChild(newElement); }else {} } </script> <form> <label>option1 <input type=checkbox name=chk1 onclick="return validate(chk1);"></label> <label>option2 <input type=checkbox name=chk2 onclick="return validate(chk2);"></label> </form> <div id="text"></div> Sorry for the language errors Regards. I tried the following code based on a post I saw somewhere else about summing all the elements of an array together. When I tried it though I couldn't seem to get it working. Can someone please point out what I did wrong or tell me a different way to sum array elements together? Thanks. Code: <script type="text/javascript"> Array.prototype.sum = function() { for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]); return sum; } var myArray=[1,2,3,4,5]; document.write(myArray.prototype.sum); </script> Ok so I have these elements on my page: Code: <input type="text" size="5" name="val[]" value="'.$NotaMaxima.'"> I want to loop through each one and take their number add it to another number set in a variable elsewhere and then alert that number. The amount of these elements on the page changes constantly, so I can't count on that. It has to loop through each one to find the values. I tried this: Code: var els,i,asig; els=document.getElementsByTagName('val'); for(i in els) { asig = parseInt(els[i].value) - parseInt(asig); } alert(asig); But no go, any ideas? Alright,ill go straight to the problem. I want to get all the elements with a certain tag.However i can only get the first one. my code: Code: function getTags(tag) { var x = document.getElementsByTagName(tag); var y = x.length; for(var i = 0; i <= y;i++) { return x[i]; } } Hi There I am trying to create some ajax/javascript to append the scriptaculous Draggable to a number of div elements with a className of draggable. The problem is i need to get the id's of each element to make them draggable, as simply making all div elements on the page draggable would effect other elements on the page which I dont want to be so. I need to:- 1.create a collection of div elements with className - draggable 2. make a list of all the element id's 3. make all elements with said id's draggable I have left out the draggable part from the code, I have simply been trying to get the element id's to display so far Code: var dv; var dh; dv = document.getElementsByTagName('div'); if (dv.className == 'draggable') { for (var i = 0; i <= dv.length; i++) { dh = dv[i].getAttribute('id'); for (var j = 0; j <= dh.length;j++) { document.getElementById('content').innerHTML = dh[j].getAttribute('id'); } } } else { alert ("no id"); } I keep getting the alert message "no id" loaded Hi again!! This is my code to add and delete dynamic rows and auto calculate the amount field by multiplying qty and rate. PHP Code: <form name="staff_reg" action="<?php echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']; ?>" method="post" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <table border="0" cellpadding="1" cellspacing="0" class="normal-text" align="left"> <tr align="center"> <td width="10" class="forhead" style="white-space:nowrap;"> </td> <td width="92" class="forhead" style="white-space:nowrap;">Qty</td> <td width="94" class="forhead" style="white-space:nowrap;">Rate</td> <td width="94" class="forhead" style="white-space:nowrap;">Amount</td> </tr> </table> <tr align="left"> <td class="forhead" style="white-space:nowrap;"><input type="button" value="Add Row" onClick="addRow('dataTable')" > <input type="button" value="Delete Row" onclick="deleteRow('dataTable')" ></td> <table border="0" id="dataTable" cellpadding="1" cellspacing="0" class="normal-text"> <tr> <td width="10" class="forhead" style="white-space:nowrap;"><input type="checkbox" name="chk[]"/></td> <td width="92" class="forhead" style="white-space:nowrap;"> <input type="text" name="qty[]" style="width:80px;" onblur=""> </td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" name="rate[]" style="width:80px;" value=""></td> <td width="94" class="forhead" style="white-space:nowrap;"> <input type="text" onblur="getValues('qty[]','rate[]','amt[]')" name="amt[]" style="width:80px;"></td> </tr> </table> <table border="0"> <tr> <td>Total:</td> <td><input type="text" name="total[]" style="width:80px;" value=""></td> </tr> <tr> <td colspan="2"> <input name="Submit" type="submit" value="Save" style="text-decoration:none" /> <input type="reset" value="Cancel" onclick="window.location.href='<?php echo $_SERVER['PHP_SELF'];?>'"> </td> </tr> </form> <script type="text/javascript"> function getValues(objName,objName2,objName3) { var var3 = ""; var arr = new Array(); arr = document.getElementsByName(objName); arr2 = document.getElementsByName(objName2); arr3 = document.getElementsByName(objName3); for(var i = 0; i < arr.length; i++) { for(var i = 0; i < arr2.length; i++) { for(var i = 0; i < arr3.length; i++) { var obj1 = document.getElementsByName(objName2).item(i); var var2 = obj1.value; var obj = document.getElementsByName(objName).item(i); var var1 = obj.value; var obj3 = document.getElementsByName(objName3).item(i); var var3 = obj3.value; var var4 = var1 * var2; document.getElementsByName(objName3).item(i).value=var4; } } } } function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes); switch(newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if (null != chkbox && true == chkbox.checked) { if (rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } } catch(e) { alert(e); } } </script> I would like to know that how can I show the value of all the elements in array "amount" in total field?? Hi, I was trying to code a draggable div, but ran into a weird behavior until I added "return false;" or rather "preventDefault();" to my onmousedown function. Now, I wonder why I need to prevent the default action for onmousedown triggered on a div. I understand what it usually does (e.g. preventing a form from submitting, etc.) But what default action is actually being prevented in this case? Thanks for your help. Here's the script: Code: <script type="text/javascript"> var dragging = false; var draggable; window.onload = function() { draggable = document.getElementById('draggable'); draggable.onmousedown = function(e) { dragging = true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } } window.onmousemove = function(e) { if (!e) e = window.event; if (dragging) { draggable.style.left = e.clientX - 30 + 'px'; draggable.style.top = e.clientY - 30 + 'px'; } } window.onmouseup = function() { dragging = false; } </script> And the HTML code: Code: <div id="draggable"></div> Hi folks! I want to display some information in a DIV (div1) that is originally hidden, display it when I hover my mouse over another DIV (div2), and hide it (div1) again when my mouse leaves that specific DIV (div2). My problem is that the onMouseOver and onMouseOut events are fired each time the mouse hovers another element within the div (such as <p> or <a> tags) which is, as far as I understood, a normal behavior, although it looks like a bug. Since the onMouseOver event will trigger an AJAX function and will retrieve some data from my db, I don't want it to be called like 5 times because the user just moved his mouse around, within the DIV and hovered different child elements. I have found this bit of code which is supposed to resolve this issue: PHP 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 } My question is: how do I call this function from my DIV, knowing that originally I have something like: <div id="div2" onMouseOut="hideDiv('div1')"></div> hideDiv being my javascript function that sets div_x to display = none How would I link these 2 functions together? And also is this going to fix the onMouseOver issue at the same time (if the mouse doesn't go out, does it mean it's still in?)? Sorry, my knowledge of javascript is kind of ltd! Thanks in advance for helping me! Arnaud hello, would anyone be able to share with me a concept of how to build a vertical navigation bar that allows you to hover over the section and a hidden area with links would appear? thank you Hey guys. I need a little help with checking elements in my array. I created an array of size 50 and initialized all elements to 1. What i want to do is if the user types in the number "1" into the prompt box, i want it to check the first 15 elements and increase only one of the elements by 1, and if the element has already been increased by 1 then i want it to check the next element and see if its been increased, if the element has been increased then it needs to move on to the next one and check that. If the element is 1, then it can be increased by "1", if the element is 2 then i need it to check the next element. If all elements within the first 15 have increased by 1, it should just alert the user that all slots have been assigned. Is there a way to do this? Thanks for your time
Hi, I'm pulling my hair out to create a simple function! I am creating an array based on form elements. I then am trying to create an IF (and nested IF) statement to check if the fields are empty and then with the nested IF statement use certain fields to create mathematical functions. So far I have this: function QuantityMWh(form) { var formchk = document.forms[0] for (i = 0; i < formchk.elements.length; i++) { if (formchk.elements[1].value == "" && formchk.elements[2].value == "") { alert("Please fill out all fields.") break } } } It's only checking the first field and not the second, and vice versa. i.e. if only one field has text then it passes. What am I doing wrong? Thanks. Hello, Could you pls tell me how to remove created element here by clicking "remove" button. I coulnt write anything I mean I tried something but couldnt manage. //document.getElementById(elementId).removeChild(newdiv); and could you also tell me how to collect datas in "myInputs[]2" text fields. I mean I need to calculate sum of all "myInputs[]2" text s values. Code: <script type="text/javascript"> var newdiv = document.createElement('div'); var count = 1; var limit = 10; function add(divName){ if (sayac == limit) { alert("Message"); } else { newdiv.innerHTML = "Halı " + (sayac + 1) + " <br>\n\ <input type='text' name='myInputs[]'>m2\n\ <select id='selBidReceivedIsPM' name='selBidReceivedIsPM'>" + "<option value='3'>Mad</option>" + "<option value='5'>Is</option></select>\t\<input type='text' name='myInputs[]2'>"; document.getElementById(divName).appendChild(newdiv); //document.getElementById(elementId).appendChild(slt); ++count; } } function remove(){ } </script> <div id="dynamicInput"> Halı 1<br><input type="text" name="myInputs[]">m2 <select id="slt"> <option value="3">Mad</option> <option value="5">Is</option> </select> <input type="text" name="myInputs[]2"> <input type="button" value="Add" onClick="add('dynamicInput');"> <input type="button" value="Remove" onClick="remove()"> </div> |