Search Results

Search found 76 results on 4 pages for 'createtextnode'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Why can't I dynamically add rows to a HTML table using JavaScript in Internet Explorer?

    - by karlthorwald
    In Firefox it works, in my Internet Explorer 6 or 7 it doesn't: <html> <head> <script type="text/javascript"> function newLine() { var tdmod = document.createElement('td'); tdmod.appendChild(document.createTextNode("dynamic")); var tr = document.createElement('tr'); tr.appendChild(tdmod); var tt = document.getElementById("t1"); tt.appendChild(tr); } </script> </head> <body> <a href="#" onclick="newLine()">newLine</a> <table id="t1" border="1"> <tr> <td> static </td> </tr> </table> </body> The user clicks on the link "newLine" and new rows should be added to the table. How to make this work also in IE? Edit: Thanks to the accepted answer I changed it like this and now it works: <table border="1"> <tbody id="t1"> <tr> <td> static </td> </tr> </tbody> </table>

    Read the article

  • javascript freezeing ie8

    - by florin
    Can someone tell me why does this code freeze ie8? It is supposed to generate input fields. In firefox, safari, chrome it works, but in in8 when i press generate button it freezes var monthNames = [ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" ]; function buildMonthlyEntries() { var startDate = new Date(document.getElementById('datastart').value); var endDate = new Date(document.getElementById('dataend').value); if (startDate == "Invalid Date" || endDate == "Invalid Date") { return null; } var monthlyEntries = document.getElementById('monthlyEntries'); monthlyEntries.innerHTML = ""; // inclusiv dataend endDate.setMonth(endDate.getMonth() + 1); // start with startDate; loop until we reach endDate for (var dt = startDate; ! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() ); dt.setMonth( dt.getMonth() + 1 ) ) { monthlyEntries.appendChild( document.createTextNode( monthNames[dt.getMonth()] + " " + String(dt.getFullYear()).substring(2) ) ); var textElement = document.createElement('input'); var textElement2 = document.createElement('input'); var textElement3 = document.createElement('input'); textElement.setAttribute('type', 'text'); //textElement.setAttribute('name', 'entry['+ monthNames[dt.getMonth()] + + String(dt.getFullYear()).substring(2) + ']'); textElement.setAttribute('name', 'entry[]'); textElement2.setAttribute('type', 'hidden'); textElement2.setAttribute('name', 'luna[]'); textElement2.setAttribute('value', '' + monthNames[dt.getMonth()] + ''); textElement3.setAttribute('type', 'hidden'); textElement3.setAttribute('name', 'an[]'); textElement3.setAttribute('value', '' + String(dt.getFullYear()) + ''); monthlyEntries.appendChild(textElement); monthlyEntries.appendChild(textElement2); monthlyEntries.appendChild(textElement3); // adauga br // monthlyEntries.appendChild(document.createElement("br")); } return null; }

    Read the article

  • how to generate tinymce to ajax generated textarea

    - by Jai_pans
    Hi, i have a image multi-uloader script which also each item uploaded was preview 1st b4 it submitted and each images has its following textarea which are also generated by javascript and my problem is i want to use the tinymce editor to each textarea generated by the ajax. Any help will be appreciated.. here is my script function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) { errorName = "You have attempted to queue too many files."; } if (errorName !== "") { alert(errorName); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: alert(message); break; } addImage("images/" + imageName); } catch (ex) { this.debug(ex); } } function fileDialogComplete(numFilesSelected, numFilesQueued) { try { if (numFilesQueued 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setProgress(percent); if (percent === 100) { progress.setStatus("Creating thumbnail..."); progress.toggleCancel(false, this); } else { progress.setStatus("Uploading..."); progress.toggleCancel(true, this); } } catch (ex) { this.debug(ex); } } function uploadSuccess(file, serverData) { try { var progress = new FileProgress(file, this.customSettings.upload_target); if (serverData.substring(0, 7) === "FILEID:") { addRow("tableID","thumbnail.php?id=" + serverData.substring(7),file.name); //setup(); //generateTinyMCE('itemdescription[]'); progress.setStatus("Thumbnail Created."); progress.toggleCancel(false); } else { addImage("images/error.gif"); progress.setStatus("Error."); progress.toggleCancel(false); alert(serverData); } } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued 0) { this.startUpload(); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.setStatus("All images received."); progress.toggleCancel(false); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Cancelled"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Stopped"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert(message); break; } addImage("images/" + imageName); } catch (ex3) { this.debug(ex3); } } function addRow(tableID,src,filename) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); rowCount + 1; row.id = "row"+rowCount; var cell0 = row.insertCell(0); cell0.innerHTML = rowCount; cell0.style.background = "#FFFFFF"; var cell1 = row.insertCell(1); cell1.align = "center"; cell1.style.background = "#FFFFFF"; var imahe = document.createElement("img"); imahe.setAttribute("src",src); var hidden = document.createElement("input"); hidden.setAttribute("type","hidden"); hidden.setAttribute("name","filename[]"); hidden.setAttribute("value",filename); /*var hidden2 = document.createElement("input"); hidden2.setAttribute("type","hidden"); hidden2.setAttribute("name","filename[]"); hidden2.setAttribute("value",filename); cell1.appendChild(hidden2);*/ cell1.appendChild(hidden); cell1.appendChild(imahe); var cell2 = row.insertCell(2); cell2.align = "left"; cell2.valign = "top"; cell2.style.background = "#FFFFFF"; //tr1.appendChild(td1); var div2 = document.createElement("div"); div2.style.padding ="0 0 0 10px"; div2.style.width = "400px"; var alink = document.createElement("a"); //alink.style.margin="40px 0 0 0"; alink.href ="#"; alink.innerHTML ="Cancel"; alink.onclick= function () { document.getElementById(row.id).style.display='none'; document.getElementById(textfield.id).disabled='disabled'; }; var div = document.createElement("div"); div.style.margin="10px 0"; div.appendChild(alink); var textfield = document.createElement("input"); textfield.id = "file"+rowCount; textfield.type = "text"; textfield.name = "itemname[]"; textfield.style.margin = "10px 0"; textfield.style.width = "400px"; textfield.value = "Item Name"; textfield.onclick= function(){ //textfield.value=""; if(textfield.value=="Item Name") textfield.value=""; if(desc.innerHTML=="") desc.innerHTML ="Item Description"; if(price.value=="") price.value="Item Price"; } var desc = document.createElement("textarea"); desc.name = "itemdescription[]"; desc.cols = "80"; desc.rows = "4"; desc.innerHTML = "Item Description"; desc.onclick = function(){ if(desc.innerHTML== "Item Description") desc.innerHTML = ""; if(textfield.value=="Item name" || textfield.value=="") textfield.value="Item Name"; if(price.value=="") price.value="Item Price"; } var price = document.createElement("input"); price.id = "file"+rowCount; price.type = "text"; price.name = "itemprice[]"; price.style.margin = "10px 0"; price.style.width = "400px"; price.value = "Item Price"; price.onclick= function(){ if(price.value=="Item Price") price.value=""; if(desc.innerHTML=="") desc.innerHTML ="Item Description"; if(textfield.value=="") textfield.value="Item Name"; } var span = document.createElement("span"); span.innerHTML = "View"; span.style.width = "auto"; span.style.padding = "10px 0"; var view = document.createElement("input"); view.id = "file"+rowCount; view.type = "checkbox"; view.name = "publicview[]"; view.value = "y"; view.checked = "checked"; var div3 = document.createElement("div"); div3.appendChild(span); div3.appendChild(view); var div4 = document.createElement("div"); div4.style.padding = "10px 0"; var span2 = document.createElement("span"); span2.innerHTML = "Default Display"; span2.style.width = "auto"; span2.style.padding = "10px 0"; var radio = document.createElement("input"); radio.type = "radio"; radio.name = "setdefault"; radio.value = "y"; div4.appendChild(span2); div4.appendChild(radio); div2.appendChild(div); //div2.appendChild(label); //div2.appendChild(table); div2.appendChild(textfield); div2.appendChild(desc); div2.appendChild(price); div2.appendChild(div3); div2.appendChild(div4); cell2.appendChild(div2); } function addImage(src,val_id) { var newImg = document.createElement("img"); newImg.style.margin = "5px 50px 5px 5px"; newImg.style.display= "inline"; newImg.id=val_id; document.getElementById("thumbnails").appendChild(newImg); if (newImg.filters) { try { newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'; } } else { newImg.style.opacity = 0; } newImg.onload = function () { fadeIn(newImg, 0); }; newImg.src = src; } function fadeIn(element, opacity) { var reduceOpacityBy = 5; var rate = 30; // 15 fps if (opacity < 100) { opacity += reduceOpacityBy; if (opacity > 100) { opacity = 100; } if (element.filters) { try { element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')'; } } else { element.style.opacity = opacity / 100; } } if (opacity < 100) { setTimeout(function () { fadeIn(element, opacity); }, rate); } } /* ************************************** * FileProgress Object * Control object for displaying file info * ************************************** */ function FileProgress(file, targetID) { this.fileProgressID = "divFileProgress"; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var progressCancel = document.createElement("a"); progressCancel.className = "progressCancel"; progressCancel.href = "#"; progressCancel.style.visibility = "hidden"; progressCancel.appendChild(document.createTextNode(" ")); var progressText = document.createElement("div"); progressText.className = "progressName"; progressText.appendChild(document.createTextNode(file.name)); var progressBar = document.createElement("div"); progressBar.className = "progressBarInProgress"; var progressStatus = document.createElement("div"); progressStatus.className = "progressBarStatus"; progressStatus.innerHTML = "&nbsp;"; this.fileProgressElement.appendChild(progressCancel); this.fileProgressElement.appendChild(progressText); this.fileProgressElement.appendChild(progressStatus); this.fileProgressElement.appendChild(progressBar); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(targetID).appendChild(this.fileProgressWrapper); fadeIn(this.fileProgressWrapper, 0); } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name; } this.height = this.fileProgressWrapper.offsetHeight; } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setStatus = function (status) { this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; if (swfuploadInstance) { var fileID = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { swfuploadInstance.cancelUpload(fileID); return false; }; } }; i am using a swfuploader an i jst added a input fields and a textarea when it preview the images which ready to be uploaded and from my html i have this script var swfu; window.onload = function () { swfu = new SWFUpload({ // Backend Settings upload_url: "../we_modules/upload.php", // Relative to the SWF file or absolute post_params: {"PHPSESSID": ""}, // File Upload Settings file_size_limit : "20 MB", // 2MB file_types : "*.*", //file_types : "", file_types_description : "jpg", file_upload_limit : "0", file_queue_limit : "0", // Event Handler Settings - these functions as defined in Handlers.js // The handlers are not part of SWFUpload but are part of my website and control how // my website reacts to the SWFUpload events. //file_queued_handler : fileQueued, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // Button Settings button_image_url : "../we_modules/images/SmallSpyGlassWithTransperancy_17x18.png", // Relative to the SWF file button_placeholder_id : "spanButtonPlaceholder", button_width: 180, button_height: 18, button_text : 'Select Files(2 MB Max)', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt;cursor:pointer } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 0, button_text_left_padding: 18, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, // Flash Settings flash_url : "../swfupload/swfupload.swf", custom_settings : { upload_target : "divFileProgressContainer" }, // Debug Settings debug: false }); }; where should i put on the tinymce function as you mention below?

    Read the article

  • Colorbox class don't work with ajax/dom object

    - by almal
    i usually use colorbox tool for open "popup windows" in my page and all are fine. In my new project the situation is little different because i use js/ajax/dom for create dinamically my objects in handleRequestStateChange() function. After import js,jquery and css for colorbox, in the head of my js page i write: $(document).ready(function () { $(window).scroll(function () { //oP1 = document.createTextNode(posizione_menu.offsetTop); //divIpt.appendChild(oMtx1); $(".divHcss").css("position", "fixed").css("top", "0px").css("z-index", "999"); }); //Examples of how to assign the Colorbox event to elements $(".group1").colorbox({rel:'group1'}); $(".group2").colorbox({rel:'group2', transition:"fade"}); $(".group3").colorbox({rel:'group3', transition:"none", width:"75%", height:"75%"}); $(".group4").colorbox({rel:'group4', slideshow:true}); $(".ajax").colorbox(); $(".youtube").colorbox({iframe:true, innerWidth:640, innerHeight:390}); $(".vimeo").colorbox({iframe:true, innerWidth:500, innerHeight:409}); $(".iframe").colorbox({iframe:true, width:"80%", height:"80%"}); $(".inline").colorbox({inline:true, width:"50%"}); $(".callbacks").colorbox({ onOpen:function(){ alert('onOpen: colorbox is about to open'); }, onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); }, onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); }, onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); }, onClosed:function(){ alert('onClosed: colorbox has completely closed'); } }); $('.non-retina').colorbox({rel:'group5', transition:'none'}) $('.retina').colorbox({rel:'group5', transition:'none', retinaImage:true, retinaUrl:true}); //Example of preserving a JavaScript event for inline calls. $("#click").click(function(){ $('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here."); return false; }); }); and after in handleRequestStateChange() i create my a element and assign to a div: var a = createElement('a'); //a.style.display = "block"; a.setAttribute('class','iframe'); a.setAttribute('href',"php/whois.php?P1="+oStxt.value); var divIp3 = createElement('div', 'divIp3', 'divIp3css'); var divIp31 = createElement('div', 'divIp31', 'divIp31css'); divIp3.appendChild(divIp31); divIp3.appendChild(a); a.appendChild(divIp31); The divIp31 become linkable but the href open page in a normal browser tab and not using attribute class for colorbox. Someone have an idea about? Thanks in advance AM

    Read the article

  • Would Apache running on port 8080 prevent dynamically loaded scripts in JavaScript?

    - by editor
    Had a nice PHP/HTML/JS prototype working on my personal Linode, then tried to throw it into a work machine. The page adds a script tag dynamically with some JavaScript. It's a bunch of Google charts that update based on different timeslices. That code looks something like this: // jQuery $.post to send the beginning and end timestamps $.post("channel_functions.php", data_to_post, function(data){ // the data that's returned is the javascript I want to load var script = document.createElement('script'); var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); var text = document.createTextNode(data); script.type= 'text/javascript'; script.id = 'chart_data'; script.appendChild(text); // Adding script tag to page head.appendChild(script); // Call the function I know were present in the script tag loadTheCharts(); }); function loadTheCharts() { // These are the functions that were loaded dynamically // By this point the script tag is supposed be loaded, added and eval'd function1(); function2(); } Function1() and function2() don't exist until they get added to the dom, but I don't call loadTheCharts() until after the $.post has run so this doesn't seem to be a problem. I'm one of those dirty PHP coders you mother warned you about, so I'm not well versed in JavaScript beyond what I've read in the typical go-to O'Reilly books. But this code worked fine on my personal dev server, so I'm wondering why it wouldn't work on this new machine. The only difference in setup, from what I can tell, is that the new machine is running on port 8080, so it's 192.168.blah.blah:8080/index.php instead of nicedomain.com/index.php. I see the code was indeed added to the dom when I use webmaster tools to "view generated source" but in Firebug I get an error like "function2() is undefined" even though my understanding was that all script tags are eval'ed when added to . My question: Given what I've laid out, and that the machine is running on :8080, is there a reason anyone can think of as to why a dynamically loaded function like function2() would be defined on the Linode and not on the machine running Apache on 8080?

    Read the article

  • javascript select box hanging on second select in ie7

    - by bsandrabr
    I have a drop down select box inside a div. When the user clicks on change, a dropdown box appears next to the change/submit button and the user makes a selection which then updates the db and the selection appears instead of the dropdown. All works fine in IE8 and firefox but in IE7 it allows one selection (there are several identical dropdowns) but the second time a selection is made it hangs on please wait. This is the relevant code <td width=200> <input type="button" onclick="startChanging(this)" value="Change" /></td> <script type="text/javascript"> var selectBox, isEditing = false; var recordvalue; if( window.XMLHttpRequest ) { recordvalue = new XMLHttpRequest(); } else if( window.ActiveXObject ) { try { recordvalue = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} } window.onload = function () { selectBox = document.getElementById('changer'); selectBox.id = ''; selectBox.parentNode.removeChild(selectBox); }; function startChanging(whatButton) { if( isEditing && isEditing != whatButton ) { return; } //no editing of other entries if( isEditing == whatButton ) { changeSelect(whatButton); return; } //this time, act as "submit" isEditing = whatButton; whatButton.value = 'Submit'; var theRow = whatButton.parentNode.parentNode; var stateCell = theRow.cells[3]; //the cell that says "present" stateCell.className = 'editing'; //so you can use CSS to remove the background colour stateCell.replaceChild(selectBox,stateCell.firstChild); //PRESENT is replaced with the select input selectBox.selectedIndex = 0; } function changeSelect(whatButton) { isEditing = true; //don't allow it to be clicked until submission is complete whatButton.value = 'Change'; var stateCell = selectBox.parentNode; var theRow = stateCell.parentNode; var editid = theRow.cells[0].firstChild.firstChild.nodeValue; //text inside the first cell var value = selectBox.firstChild.options[selectBox.firstChild.selectedIndex].value; //the option they chose selectBox.parentNode.replaceChild(document.createTextNode('Please wait...'),selectBox); if( !recordvalue ) { //allow fallback to basic HTTP location.href = 'getupdate.php?id='+editid+'&newvalue='+value; } else { recordvalue.onreadystatechange = function () { if( recordvalue.readyState != 4 ) { return; } if( recordvalue.status >= 300 ) { alert('An error occurred when trying to update'); } isEditing = false; newState = recordvalue.responseText.split("|"); stateCell.className = newState[0]; stateCell.firstChild.nodeValue = newState[1] || 'Server response was not correct'; }; recordvalue.open('GET', "getupdate.php?id="+editid+"&newvalue="+value, true); recordvalue.send(null); } } </script> If anyone has any idea why this is happening I'd be very grateful

    Read the article

  • Accessing contents of NativeWindow in a HTML AIR application?

    - by Dan Scotton
    I'm currently building a HTML/JS AIR application. The application needs to display to the user a different 'window' - dependant on whether this is the first time they've launched the application or not. This part is actually fine and I have the code below to do that: if(!startUp()) { // this simply returns a boolean from a local preferences database that gets shipped with the .air // do first time stuff var windowOptions = new air.NativeWindowInitOptions(); windowOptions.systemChrome = 'none'; windowOptions.type = 'lightweight'; windowOptions.transparent = 'true'; windowOptions.resizable = 'false'; var windowBounds = new air.Rectangle(300, 300, 596, 490); var newHtmlLoader = air.HTMLLoader.createRootWindow(true, windowOptions, true, windowBounds); newHtmlLoader.load(new air.URLRequest('cover.html')); } else { // display default window // just set nativeWindow.visible = true (loaded from application.xml) } However, what I want to be able to do is manipulate the html content from within cover.html after it has loaded up. There seems to be plenty of tutorials online of how to move, resize, etc. the NativeWindow, but I simply want access to the NativeWindow's HTML content. For example, how would I add a new paragraph to that page? I've tried the following: newHtmlLoader.window.opener = window; var doc = newHtmlLoader.window.opener.document.documentElement; Using AIR's Introspector console, ....log(doc) returns [object HTMLHtmlElement]. Hmm, seems promising right? I then go on to try: var p = document.createElement('p'); var t = document.createTextNode('Insert Me'); p.appendChild(t); doc.appendChild(p); ...but nothing gets inserted. I've also tried the following replacements for doc: var doc = newHtmlLoader.window.opener.document.body; // .log(doc) -> [object HTMLBodyElement] var doc = newHtmlLoader.window.opener.document; // .log(doc) -> Error: HIERARCHY_REQUEST_ERR: DOM Exception 3 ...as well as the following with jQuery: $(doc).append('<p>Insert Me</p>'); // again, nothing So, anyone had any experience in accessing a NativeWindow's inner content programmatically? Any help will be greatly appreciated.

    Read the article

  • javascript problem

    - by Gourav
    I have created a dynamic table whose rows gets appended by click of the "Add" button, i want the user not to be able to submit the page if no value is entered in all the rows of the table. how do i achieve this The code is <html> <head> <script type="text/javascript"> function addRowToTable() { var tbl = document.getElementById('tblSample'); var lastRow = tbl.rows.length; var iteration = lastRow+1; var row = tbl.insertRow(lastRow); var cellLeft = row.insertCell(0); var textNode = document.createTextNode(iteration); cellLeft.appendChild(textNode); var cellRight = row.insertCell(1); var el = document.createElement('input'); el.type = 'text'; el.name = 'txtRow' + iteration; el.id = 'txtRow' + iteration; el.size = 40; cellRight.appendChild(el); } function validation() { var a=document.getElementById('tblSample').rows.length; for(i=0;i<a;i++) { alert(document.getElementById('tblSample').txtRow[i].value);//this doesnt work } return true; } </script> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form name ='qqq' action="sample.html"> <p> <input type="button" value="Add" onclick="addRowToTable();" /> <input type="button" value="Submit" onclick="return validation();" /> </p> <p> <table border="1" id="tblSample"> <tr> <td>1</td> <td>The 1st row</td> </tr> </table> </p> </form> </body> </html> Please suggest

    Read the article

  • C# xml Class to substitute ini files

    - by Eduardo
    Hi guys, I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files. I already did something and it is working but I am having trouble when I need to create different groups, something like this: <?xml version="1.0" encoding="utf-8"?> <CONFIG> <General> <Field1>192.168.0.2</Field1> </General> <Data> <Field1>Joseph</Field1> <Field2>Locked</Field2> </Data> </CONFIG> how can i specify that i want to read the field1 of [data] group? note that i have same field name in both groups (Field1)! I am using System.Linq, something like this: To open document: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(FilePath); To save document: xmlDoc.Save(FilePath); To get value: public string getValue(string Field) { string result = ""; try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) result = ""; else result = xmlComum.Item(0).InnerText; } catch (Exception ex) { return ""; } return result; } To set value: public void setValue(string Group, string Field, string FieldValue) { try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) { xmlComum = xmlDoc.GetElementsByTagName(Group); if (xmlComum.Item(0) == null) { // create group createGroup(Group); xmlComum = xmlDoc.GetElementsByTagName(Group); } XmlElement xmlE = xmlDoc.CreateElement(Field); XmlText xmlT = xmlDoc.CreateTextNode(FieldValue); xmlE.AppendChild(xmlT); xmlComum.Item(0).AppendChild(xmlE); } else { // item already exists, just change its value xmlComum.Item(0).InnerText = Value; } xmlDoc.Save(FilePath); } catch (Exception ex) { } } The CreateGroup code: public void createGroup(string Group) { try { XmlElement xmlComum = xmlDoc.CreateElement(Group); xmlDoc.DocumentElement.AppendChild(xmlComum); xmlDoc.Save(FilePath); } catch (Exception ex) { } } Thank You!

    Read the article

  • adding results of XML request to a page

    - by user2925833
    I am trying to get a feel for adding content to a page with XMLHTTPRequest. I would like to add the results to existing page content say in a second column, but I am not having any luck. I would appreciate a shove in the right direction. Thanks for any help. <!DOCTYPE html> <html> <head> <style> #button{ float: left; } #team{ float: left; } </style> <title>XMLHTTPRequest</title> <script src="jquery-1.10.2.js"></script> <script> $(document).ready(function(){ xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4 && xhr.status == 200) { xmlDoc = xhr.responseXML; var team = xmlDoc.getElementsByTagName("teammember"); var html = ""; for (i = 0; i < team.length; i++){ html += xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue + "<br>" + xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue + "<br>" + xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue + "<br><br>"; } //this is the code I would like help with var team = document.getElementById("team"); team.appendChild(document.createTextNode("html")); } } xhr.open("GET", "team.xml", true); }); </script> </head> <body> <div id="button"> <button onclick="xhr.send()">Click Me!</button> </div> <div id="team"> </div> </body> </html>

    Read the article

  • (PHP) 1)How to genrate Secreate key on User & Client Side ? 3) How to Compare Server side MD5 and Client side Md5 ?

    - by user557994
    /* In Below Code .. My problem is that 1) How to genrate Secreate key on User Side ? 2) How to genrate Secreate key on Client Side ? 3) How to Compare Server side MD5 and Client side Md5 ? Can you solve my problem ? */ $gid = $_GET['id']; if($gid=="") { $filename = "counter.txt"; $fp = fopen( $filename, "r" ) or die("Couldn't Generate Whiteboard"); while ( ! feof( $fp ) ) { $countfile = fgets( $fp); $countfile++; } fclose( $fp ); $fp = fopen( $filename, "w" ) or die("Couldn't generate whiteboard"); fwrite( $fp, $countfile ); fclose( $fp ); $doc = new DOMDocument('1.0', 'UTF-8'); $ele = $doc-createElement( 'root' ); $ele-nodeValue = $uvar; $doc-appendChild( $ele ); $test = $doc-save("$countfile.xml"); genkey($id); echo ""; $uvar=$_POST['msgval']; exit; } else { if($uvar == "") { $xdoc = new DOMDocument( '1.0', 'UTF-8' ); $xdoc-Load("$gid.xml"); $candidate = $xdoc-getElementsByTagName('root')-item(0); $newElement = $xdoc -createElement('root'); $txtNode = $xdoc -createTextNode ($root); $newElement - appendChild($txtNode); $candidate - appendChild($newElement); $msg = $candidate-nodeValue; } } function genkey($id) { $encrypt_key = "GJHsahakst1468464a"; $key = MD5("$id","$$encrypt_key"); return $key; } ? function sendRequest() { var uvar = document.getElementById('txtHint').value; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status==200) { document.getElementById('txtHint').value = ""; } } xmlhttp.open("POST","post.php?id=",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("umsg="+uvar); return; } Msg " /

    Read the article

  • How to read & write contents of a div from localstorage in chrome extensions?

    - by Minas Abovyan
    I am trying to build an extension that will allow users to put some parameters into a text box in the popup, generate a link using that information and add it to the said popup. I have all that working, but needless to say, it gets flushed every time the user opens the extension anew. I'd like the info that has been put in there to stay, but can't seem to get it to work. Here's what I have thus far: manifest.json { "manifest_version": 2, "name": "Test", "description": "Test Extension", "version": "1.0", "permissions": [ "http://*/*", "https://*/*" ], "browser_action": { "default_title": "This is a test", "default_popup": "popup.html" } } popup.html <!DOCTYPE html> <html> <head> </head> <body> <div id="linkContainer"/> <input type="text" id="catsList"/> <button type="button" id="addToList">Add</button> <script src="popup.js"></script> </body> </html> popup.js function addCats() { var a = document.createElement('a'); a.appendChild(document.createTextNode(document.getElementById('catsList').value)); a.setAttribute('href', 'http://google.com'); var p = document.createElement('p'); p.appendChild(a) document.getElementById('linkContainer').appendChild(p); indexLinks() } function indexLinks() { var links = document.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { (function () { var ln = links[i]; var location = ln.href; ln.onclick = function () { chrome.tabs.create({active: true, url: location}); }; })(); } }; document.getElementById('addToList').onclick = addCats; My guess is that I need something along the lines of localStorage['cointainer'] = document.getElementById('linkContainer'); at the end of addCats() and a call to something like function loadLocalStorage() { var container = document.getElementById('linkContainer'); container.innerHTML = localStorage['container']; } at the beginning, but doing that didn't work. Not sure what's going wrong. Also,if there is a different way to save users' additions, I'd be open to them.

    Read the article

  • allignment issue of div tag

    - by Quasar the space thing
    I am trying to create a web page where on click of a button I can add div tags. What I thought to do was that I'll create two div tags within a single div so that over all presentation will be uniform and similar to a table having two columns and multiple rows and the first column contains only label's and second column will contain textbox. Here is the JS file : var counter = 0; function create_div(type){ var dynDiv = document.createElement("div"); dynDiv.id = "divid_"+counter; dynDiv.class="main"; document.body.appendChild(dynDiv); question(); if(type == 'ADDTEXTBOX'){ ADDTEXTBOX(); } counter=counter+1; } function question(){ var question_div = document.createElement("div"); question_div.class="question"; question_div.id = "question_div_"+counter; var Question = prompt("Enter The Question here:", ""); var node=document.createTextNode(Question); question_div.appendChild(node); var element=document.getElementById("divid_"+counter); element.appendChild(question_div); } function ADDTEXTBOX(){ var answer_div = document.createElement("div"); answer_div.class="answer"; answer_div.id = "answer_div_"+counter; var answer_tag = document.createElement("input"); answer_tag.id = "answer_tag_"+counter; answer_tag.setAttribute("type", "text"); answer_tag.setAttribute("name", "textbox"); answer_div.appendChild(answer_tag); var element=document.getElementById("divid_"+counter); element.appendChild(answer_div); } Here is the css file : .question { width: 40%; height: auto; float: left; display: inline-block; text-align: justify; word-wrap:break-word; } .answer { padding-left:10%; width: 40%; height: auto; float: left; overflow: auto; word-wrap:break-word; } .main { width: auto; background-color:gray; height: auto; overflow: auto; word-wrap:break-word; } My problem is that the code is working properly but both the divisions are not coming in a straight line. after the first div prints on the screen the second divisions comes in another line. How can I make both the div's come in the same line ? Thank You. PS : should I stick with the current idea of using div or should I try some other approach ? like tables ?

    Read the article

  • Javascript .removeChild() only deletes even nodes?

    - by user1476297
    first posting. I am trying dynamically add children DIV under a DIV with ID="prnt". Addition of nodes work fine no problem. However strange enough when it comes to deleted nodes its only deleting the even numbered nodes including 0. Why is this, I could be something stupid but it seem more like a bug. I could be very wrong. Please help Thank you in advance. <script type="text/javascript"> function displayNodes() { var prnt = document.getElementById("prnt"); var chlds = prnt.childNodes; var cont = document.getElementById("content"); for(i = 0; i < chlds.length; i++) { if(chlds[i].nodeType == 1) { cont.innerHTML +="<br />"; cont.innerHTML +="Node # " + (i+1); cont.innerHTML +="<br />"; cont.innerHTML +=chlds[i].nodeName; cont.innerHTML +="<br />"; } } } function deleteENodes() { var prnt = document.getElementById("prnt"); var chlds = prnt.childNodes; for(i = 0; i < chlds.length; i++) { if(!(chlds[i].nodeType == 3)) { prnt.removeChild(chlds[i]); } } } function AddENodes() { var prnt = document.getElementById("prnt"); //Only even nodes are deletable PROBLEM for(i = 0; i < 10; i++) { var newDIV = document.createElement('div'); newDIV.setAttribute("id", "c"+(i)); var text = document.createTextNode("New Inserted Child "+(i)); newDIV.appendChild(text); prnt.appendChild(newDIV); } } </script> <title>Checking Div Nodes</title> </head> <body> <div id="prnt"> Parent 1 </div> <br /> <br /> <br /> <button type="button" onclick="displayNodes()">Show Node Info</button> <button type="button" onclick="deleteENodes()">Remove All Element Nodes Under Parent 1</button> <button type="button" onclick="AddENodes()">Add 5 New DIV Nodes</button> <div id="content"> </div> </body>

    Read the article

  • touchend event doesn't work on Android

    - by Protos
    Hi, I've just started looking at doing some basic mobile web development on the android and an writing a test script to investigate the touch events. I've run the following code in the android emulator, and the touchend event never gets fired. Can anyone tell me why ? I've tried in three versions of the emulator (1.6, 2.1 and 2.2) and all three behave in the same way. Thanks in advance for any help you can give me. Cheers, Colm EDIT - I've also tried this using the XUI framework and have the same problem so I'm guessing I have a fundamental misunderstanding of how this stuff works ...... Map Test <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="language" content="english" /> <meta name="viewport" content="minimum-scale=1.0, width=device-width, height=device-height, user-scalable=no"> <script type="text/javascript"> window.onload = function(){ document.body.appendChild( document.createTextNode("w: " + screen.width + " x " + "h : " +screen.height) ); attachTouchEvents(); } function attachTouchEvents() { console = document.getElementById("console"); var map = document.getElementById("map"); map.addEventListener ('touchstart', function (event) { event.preventDefault(); var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "S : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch Start"; }, false); map.addEventListener ('touchmove', function (event) { event.preventDefault(); var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "M : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch Move"; }, false); map.addEventListener ('touchend', function (event) { var touch = event.touches[0]; document.getElementById("touchCoord").innerHTML = "E : " + touch.pageX + " " + touch.pageY; document.getElementById("touchEvent").innerHTML = "Touch End"; event.preventDefault(); }, false); console.innerHTML = "event attached"; } </script> <style type="text/css"> html, body { height:100%; width:100%; margin: 0; background-color:red; } #map { height: 300px; width: 300px; background-color:yellow; } </style> </head> <body> <div id="map"></div> <div id="touchCoord">Touch Coords</div> <div id="touchEvent">Touch Evnt</div> <div id="console">Console</div> </body>

    Read the article

  • Firefox not running jQuery for XHTML output

    - by ScottSEA
    Okay, I did a crappy job of describing the issue in my previous post. I think the discussion got sidetracked from the core issue - so I'm going to try again. Mea Culpa to Elzo Valugi about the aforementioned thread. I have an XML file: <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="wtf.xsl"?> <Paragraphs> <Paragraph>Hi</Paragraph> </Paragraphs> Simple enough. I also have a stylesheet to create XHTML output: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" omit-xml-declaration="yes"/> <xsl:template match="/*"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>FF-JS-XHTML WTF</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="wtf.js"></script> </head> <body> <xsl:apply-templates /> </body> </html> </xsl:template> <xsl:template match="Paragraph"> <p> <xsl:apply-templates /> </p> </xsl:template> </xsl:stylesheet> Last but not least, I have the following jQuery in toto (wtf.js, from the script tag in the stylesheet): $(function() { alert('Hiya!'); $('<p>Hello</p>').appendTo('body'); }); Extremely simple, but sufficient for the demonstration. When I run this in Internet Explorer, I get the alert 'Hiya!' as well as the expected: Hi Hello but when I run it in Firefox (3.0.1), I still get the alert, but the jQuery does not insert the paragraph into the DOM, and I just get this: Hi If I change the stylesheet to method="html" it works fine, and I get (along with the alert): Hi Hello Why doesn't Firefox run the jQuery with an XHTML document? Has anyone any experience with this problem? EDIT: ADDITIONAL INFO I can successfully insert elements into the documents this way in Firefox (method="xml"): var frag = document.createDocumentFragment(); var p = document.createElement('p'); p.appendChild(document.createTextNode('Ipsum Lorem')); frag.appendChild(p); $('body').append(frag); but I'm running into a similar problem with the .remove() method. It is looking more and more that Firefox doesn't construct a DOM from XML that jQuery can relate to, or somesuch.

    Read the article

  • how to create <tr> row and append/insert it into a table a run time ina web page + MSHTML

    - by madhu
    Hi I'm using IHTMLdocument2 to create Element This is my code: IHTMLdocument2 pDoc2;//it is initialized in ma code BSTR eTag = SysAllocString(L"TR"); IHTMLElement *pTRElmt = NULL; hr = pDoc2->createElement(eTag,&pTRElmt); if(FAILED(hr)) return hr; IHTMLDOMNode *pTRNode = NULL; hr = pTRElmt->QueryInterface(IID_IHTMLDOMNode, (void **)&pTRNode); if(FAILED(hr)) return hr; // create TD node IHTMLElement *pTDElmt = NULL; hr = pDoc2->createElement(L"TD",&pTDElmt); if(FAILED(hr)) return hr; IHTMLDOMNode *pTDNode = NULL; hr = pTDElmt->QueryInterface(IID_IHTMLDOMNode,(void **)&pTDNode); if(FAILED(hr)) return hr; IHTMLDOMNode *pRefNode = NULL; hr = pTRNode->appendChild(pTDNode,&pRefNode); if(FAILED(hr)) return hr; // create TEXT Node IHTMLDOMNode *pTextNode = NULL; hr = pDoc3->createTextNode(L"madhu", &pTextNode); if(FAILED(hr)) return hr; IHTMLDOMNode *pRefNod = NULL; hr = pTDNode->appendChild(pTextNode,&pRefNod); if(FAILED(hr)) return hr; //********* setting attributes for <tr> /* VARIANT bgclor; bgclor.vt = VT_I4; bgclor.lVal =0xC0C0C0; hr = newElem->setAttribute(L"bgcolor",bgclor,1); if(FAILED(hr)) return hr; VARIANT style; style.vt = VT_BSTR; style.bstrVal = SysAllocString(L"display: table-row"); hr = newElem->setAttribute(L"style",style,1); if(FAILED(hr)) return hr; VARIANT id; id.vt = VT_BSTR; id.bstrVal = SysAllocString(L"AttrRowMiddleName"); hr = newElem->setAttribute(L"id",id,1); if(FAILED(hr)) return hr; */ //create <td> for row <tr> /* VARIANT Name; Name.vt = VT_BSTR; Name.bstrVal = SysAllocString(L"MiddleName"); hr = newElem->setAttribute(L"name",Name,1); if(FAILED(hr)) return hr; VARIANT Type; Type.vt = VT_BSTR; Type.bstrVal = SysAllocString(L"text"); hr = newElem->setAttribute(L"type",Type,1); if(FAILED(hr)) return hr; VARIANT Value; Value.vt = VT_BSTR; Value.bstrVal = SysAllocString(L"button"); hr = newElem->setAttribute(L"value",Value,1); if(FAILED(hr)) return hr; */ //IHTMLDOMNode *pReturn = NULL; //hr = pParentNode->replaceChild(pdn,pFirstchild,&pReturn); //if(FAILED(hr)) // return hr; VARIANT refNode; refNode.vt = VT_DISPATCH; refNode.pdispVal = pDomNode; IHTMLDOMNode *pREfTochild = NULL; hr = pParentNode->insertBefore(pTRNode,refNode,&pREfTochild); if(FAILED(hr)) return hr; This is inserting something but not visible and inserting as and when tr tag comes I even tried with clone but same problem. pls anybody give right code for this

    Read the article

  • Checkboxes will not check in IE7 using Javascript, and yet no errors

    - by leeand00
    Okay I'm totally confused on this one. I have a script that receives a bunch of values from a JSON object and creates a bunch of checkboxes and either checks or unchecks a these checkboxes based on their values. This script treats me like a woman treats me... "If you don't know what's wrong, then I'm not going to tell you..." The script works correctly in IE8, Firefox3, etc... etc... However... In IE7 the script fails to check off the checkboxes. It displays no errors and from what I can tell, the script runs just fine. I just doesn't check any of the checkboxes, and I don't know why... shoppingCart['Update_Stock_Item_0_NRD%5FHAT2'] = { 'propeller': { 'label' : 'propeller', 'optionValues' : { 'on' : { 'selected': 'selected' }, 'off' : { 'selected': '' }, '' : new String() } }, 'sunLogo': { 'label' : 'sunLogo', 'optionValues' : { 'on' : { 'selected': 'selected' }, 'off' : { 'selected': '' }, '' : new String() } }, 'MSLogo': { 'label' : 'sunLogo', 'optionValues' : { 'on' : { 'selected': 'selected' }, 'off' : { 'selected': '' }, '' : new String() } } }; function stockInit() { alert("BEGIN: stockInit()"); // TODO: You will recieve an "on" and an "off" option, // One will have a "selected" attribute of "selected", // and the other will have a "selected" attribute of "" // // The option that has the "selected" attribute of "" // will generate a checkbox that is not checked. // // The option that has the "selected attribute of "selected" // will generate a checkbox that is checked. // // Why? You ask...because that's just the way the thing is // setup. for(var item in shoppingCart) { // // console.log("processing item: " + item); var optionContainer = document.getElementById(item + "_optionContainer"); for(var option in shoppingCart[item]) { if(option != "blank") { // // console.log("option: " + option); var currentOption = shoppingCart[item][option]['optionValues']; // // console.log("currentOption['on']['selected']: " + currentOption['on']['selected']); // // console.log("currentOption['off']['selected']: " + currentOption['off']['selected']); // Really you only have to check the one, but just to be through-o var selected = (currentOption['on']['selected'] == 'selected') ? true : false; selected = (currentOption['off']['selected'] == 'selected') ? false : true; var label = document.createElement("LABEL"); var labelText = document.createTextNode(shoppingCart[item][option]['label']); var optionInput = document.createElement("INPUT"); var hiddenInput = document.createElement("INPUT"); optionInput.setAttribute("type", "checkbox"); optionInput.checked = selected; optionInput.setAttribute("id", option); alert(optionInput.id); alert(optionInput.checked); hiddenInput.setAttribute("type", "hidden"); hiddenInput.setAttribute("name", option); hiddenInput.setAttribute("id", option + "_hiddenValue"); hiddenInput.setAttribute("value", (optionInput.checked) ? "on" : "off"); label.appendChild(optionInput); label.appendChild(labelText); label.appendChild(hiddenInput); (function(id) { optionInput.onclick = function() { var hiddenInput = document.getElementById(id + "_hiddenValue"); hiddenInput.setAttribute("value", (this.checked == true) ? "on" : "off"); alert("this.id: " + this.id); alert("this.checked: " + this.checked); } })(optionInput.id); optionContainer.appendChild(label); } } // // console.log("processing item of " + item + " complete"); } alert("END: stockInit()"); } And please don't ask why I'm doing things this way...all I can really tell you is that I don't have access to the backend code...so I get what I get...

    Read the article

  • Change the content of a <style> element through JavaScript

    - by paercebal
    The Problem I have the following code: <html> <head> <style id="ID_Style"> .myStyle { color : #FF0000 ; } </style> </head> <body> <p class="myStyle"> Hello World ! </p> </body> </html> And I want to modify the contents of <style> through JavaScript. The Expected Solution The first solution was to use the innerHTML property of the style element (retrieved through its id), but while it works on Firefox, it fails on Internet Explorer 7. So, I used pure DOM methods, that is, creating an element called style, a text node with the desired content, and append the text node as a child of the style node, etc. It fails, too. According to MSDN, the <style> element has an innerHTML property, and according to W3C, the <style> element is a HTMLStyleElement, which derives from HTMLElement, deriving from Element deriving from Node, which has the appendChild method. It seems to behave as if the content of a <style> element was readonly on Internet Explorer. The Question So the question is: Is there a way to modify the content of a <style> element on Internet Explorer? While the current problem is with IE7, a cross-browser solution would be cool, if possible. Appendix Sources: Style Element (MSDN): http://msdn.microsoft.com/en-us/library/ms535898.aspx HTMLStyleElement (W3C): http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-16428977 Complete Test Code You can use this test code if you want to reproduce your problem: <html> <head> <style id="ID_Style"> .myStyle { color : #FF0000 ; } </style> <script> function replaceStyleViaDOM(p_strContent) { var oOld = document.getElementById("ID_Style") ; var oParent = oOld.parentNode ; oParent.removeChild(oOld) ; var oNew = document.createElement("style") ; oParent.appendChild(oNew) ; oNew.setAttribute("id", "ID_Style") ; var oText = document.createTextNode(p_strContent) ; oNew.appendChild(oText) ; } function replaceStyleViaInnerHTML(p_strContent) { document.getElementById("ID_Style").innerHTML = p_strContent ; } </script> <script> function setRedViaDOM() { replaceStyleViaDOM("\n.myStyle { color : #FF0000 ; }\n") } function setRedViaInnerHTML() { replaceStyleViaInnerHTML("\n.myStyle { color : #FF0000 ; }\n") } function setBlueViaDOM() { replaceStyleViaDOM("\n.myStyle { color : #0000FF ; }\n") } function setBlueViaInnerHTML() { replaceStyleViaInnerHTML("\n.myStyle { color : #0000FF ; }\n") } function alertStyle() { alert("*******************\n" + document.getElementById("ID_Style").innerHTML + "\n*******************") ; } </script> </head> <body> <div> <button type="button" onclick="alertStyle()">alert Style</button> <br /> <button type="button" onclick="setRedViaDOM()">set Red via DOM</button> <button type="button" onclick="setRedViaDOM()">set Red via InnerHTML</button> <br /> <button type="button" onclick="setBlueViaDOM()">set Blue via DOM</button> <button type="button" onclick="setBlueViaInnerHTML()">set Blue via InnerHTML</button> </div> <p class="myStyle"> Hello World ! </p> </body> </html> Thanks !

    Read the article

  • Looping through siblings of a specific row/setting up function

    - by Matt
    Trying to work through my javascript book I am referencing to learn the language and got stuck on looping through siblings of a specific row. W3schools and W3 didnt have what i was looking for. Below is a function walk-through... It reads: Create the countRecords() function. The purpose of this function is to count the number of visible rows in the data table after the table headings. The total is then displayed in the table cell with the id "records". Add the follow commands to the function: a. Create a object named headRow that points to the table row with the id "titleRow". Create a variable named rowCount, setting its initial value to 0. b. Create a for loop that uses familial references starting with the first sibling of headRow and moving to the next sibling until there are no siblings left. Within the for loop. test whether the node name of the currentnext sibling until there are no sibilings left. Within the for loop test whether the node name of the current node is equal to "TR". If it is, test wheter the value of its display style is equal to an empty text string. If it is (indicating that it is visible in the document) increate the value of the rowCount variable by 1. c. Change the text of the "records" table cell to the value of the rowCount variable. Don't use innerHTML. Create a text node that contains the value of the rowCount variable and assign it to a variable called txt. Create a variable called record to store the reference to the element "records" table cell. d. Insert an if condition that test whether the "records" cell has any child nodes. If it does, replace the replace the text node of the "record" table cell with the created text node (txt). If it doesn't append the text node to the cell. var headRow; // part a var rowCount = 0; //part b this is where I get lost. I know I need to access the id titleRow but unsure how to set my loop up specifically for this headRow = document.getElementById("titleRow"); for(var i=0; i<headrow.length; i++) { if (something is not equal == "TH") { make code happen here } if (is "TR" == ""){ rowCount = +1; } //part c var txt = document.createTextNode(rowCount); var record = document.getElementsById("records") //part d holding off on this part until I get a,b,c figured out. The HTML supporting snippet: <table id="filters"> <tr><th colspan="2">Filter Product List</th></tr> <tr> <td>Records: </td> <td id="records"></td> </tr> <table id="prodTable"> <tr><th colspan="8">Digital Cameras</th></tr> <tr id="titleRow"> <th>Model</th> <th>Manufacturer</th> <th>Resolution</th> <th>Zoom</th> <th>Media</th> <th>Video</th> <th>Microphone</th> </tr> Thanks for the help!

    Read the article

  • PHP - DOM class - numbered entities and encodings problem

    - by user343607
    Hi guys, I'm having some difficult with PHP DOM class. I am making a sitemap script, and I need the output of $doc-saveXML() to be like <?xml version="1.0" encoding="UTF-8"?> <root> <url> <loc>http://www.somesite.com/servi&#xE7;os/redesign</loc> </url> </root> or <?xml version="1.0" encoding="UTF-8"?> <root> <url> <loc>http://www.somesite.com/servi&#231;os/redesign</loc> </url> </root> but I am getting: <?xml version="1.0" encoding="UTF-8"?> <root> <url> <loc>http://www.somesite.com/servi&amp;#xE7;os/redesign</loc> </url> </root> This is the closet I could get, using a replace named to numbered entities function. I was also able to reproduce <?xml version="1.0" ?> <root> <url> <loc>http://www.somesite.com/servi&amp;#xE7;os/redesign</loc> </url> </root> But without the encoding specified. The best solution (the way I think the code should be written) would be: <?php $myArray = array(); // do some stuff to populate the with URL strings $doc = new DOMDocument('1.0', 'UTF-8'); // here we modify some property. Maybe is the answer I am looking for... $urlset = doc->createElement("urlset"); $urlset = $doc->appendChild($urlset); foreach($myArray as $address) { $url = $doc->createElement("url"); $url = $urlset->appendChild($url); $loc = $doc->createElement("loc"); $loc = $url->appendChild($loc); $valueContent = $doc->createTextNode($value); $valueContent = $loc->appendChild($address); } echo $doc->saveXML(); ?> Notes: Server response header contains charset as UTF-8; PHP script is saved in UTF-8; URLs read are UTF-8 strings; Above script contains encoding declaration on DOMDocument constructor, and does not use any convert functions, like htmlentities, urlencode, utf8_encode... I've tried changing the DOMDocument properties DOMDocument::$resolveExternals and DOMDocument::$substituteEntities values. None combinations worked. And yes, I know I can made all process without specifying the character set on DOMDocument constructor, dump string content into a variable and make a very simple string substitution with string replace functions. This works. But I would like to know where I am slipping, how can this be made using native API's and settings, or even if this is possible. Thanks in advance.

    Read the article

  • Filter syslog in php functions, then display contents in JS div?

    - by qx3rt
    Let's revise this question with a new approach...I have three files: logtail.php, ajax.js and index.php. My goal is to create a syslog viewer (Linux). On index.php I made a div where I want to display only the filtered contents of the syslog. I must filter the contents in logtail.php. I have to use a shell_exec and | grep the contents with multiple different regexes. Right now I | grep the entire syslog file and it displays live in the log viewer, but my filters are not working as planned. I need help figuring out how to use $_GET to grab only the contents from the syslog that the user wants to see. I have a text field and submit button prepared for that in my index.php file. Should I use functions (tried this already)? Or is there a better approach? Can you give me some examples? logtail.php //Executes a shell script to grab all file contents from syslog on the device //Explodes that content into an array by new line, sorts from most recent entry to oldest entry if (file_exists($filename = '/var/log/syslog')) { $syslogContent = shell_exec("cat $filename | grep -e '.*' $filename"); $contentArray = explode("\n", $syslogContent); rsort($contentArray); print_r($contentArray); } ajax.js (working properly) function createRequest() { var request = null; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } } if (request == null) { return alert("Error creating request object!"); } else { return request; } } var request = createRequest(); function getLog(timer) { var url = 'logtail.php'; request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); startTail(timer); } function startTail(timer) { if (timer == "stop") { stopTail(); } else { t = setTimeout("getLog()",1000); } } function stopTail() { clearTimeout(t); var pause = "The log viewer has been paused. To begin viewing again, click the Start Log button.\n"; logDiv = document.getElementById("log"); var newNode = document.createTextNode(pause); logDiv.replaceChild(newNode,logDiv.childNodes[0]); } function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var currentLogValue = request.responseText.split("\n"); eval(currentLogValue); logDiv = document.getElementById("log"); var logLine = ' '; for (i = 0; i < currentLogValue.length - 1; i++) { logLine += currentLogValue[i] + "<br/>\n"; } logDiv.innerHTML = logLine; } else alert("Error! Request status is " + request.status); } } index.php <script type="text/javascript" src="scripts/ajax.js"></script> <button style="margin-left:25px;" onclick="getLog('start');">Start Log</button> <button onclick="stopTail();">Stop Log</button> <form action="" method="get"> //This is where the filter options would be Date & Time (ex. Nov 03 07:24:57): <input type="text" name="dateTime" /> <input type="submit" value="submit" /> </form> <br> <div id="log" style="..."> //This is where the log contents are displayed </div>

    Read the article

  • Intermittent Internet Explorer Error whilst using Javascript to traverse XML Nodes

    - by Sykth
    Hi there all, Basically I use a javascript SOAP plugin to send and receive XML from a web service. Recently I've been experiencing intermittment (1 in every 20-30 times) errors in IE when trying to access data in the XML file. Bear with me on this, I'm going to try and go into a fair amount of detail to help anyone who is willing to read this: I have a html file, with an external javascript file attached. In the javascript file I include 5 global variables: var soapRes; var questionXML; var xRoot; var assessnode; var edStage = 0; Once the html file is at a readystate I request the XML file from the web service like this: function initNextStage(strA) { // Set pl Parameters here var pl = new SOAPClientParameters(); // soap call var r = SOAPClient.invoke(url, "LoadAssessment", pl, true, initStage_callBack); } function initStage_callBack(r, soapResponse) { soapRes = soapResponse; initvalues(); function initvalues(){ xRoot = soapRes.documentElement; assessnode = xRoot.getElementsByTagName("ed")[0]; questionXML = assessnode.getElementsByTagName("question")[edStage]; } } Once this is completed the XML should be loaded into memory via the global variable soapRes. I then save values to the XML before moving one node down the XML tree, and pulling the next set of values out of it. function submitAns1() { var objAns; var corElem; var corElemTxt; questionXML = assessnode.getElementsByTagName("question")[edStage]; objAns = questionXML.getElementsByTagName("item")[0].getAttribute("answer"); corElem = soapRes.createElement("correct"); corElemTxt = soapRes.createTextNode("value"); questionXML.appendChild(corElem); corElem.appendChild(corElemTxt); if(objAns == "t") { corElemTxt.nodeValue = "true"; } else { corElemTxt.nodeValue = "false"; } edStage++; questionXML = assessnode.getElementsByTagName("question")[edStage]; var inc1 = questionXML.getElementsByTagName("sentence")[0]; var inc2 = questionXML.getElementsByTagName("sentence")[1]; var edopt1 = questionXML.getElementsByTagName("item")[0]; var edopt2 = questionXML.getElementsByTagName("item")[1]; var edopt3 = questionXML.getElementsByTagName("item")[2]; var edopt4 = questionXML.getElementsByTagName("item")[3]; var edopt5 = questionXML.getElementsByTagName("item")[4]; var temp1 = edopt1.childNodes[0].nodeValue; var temp2 = edopt2.childNodes[0].nodeValue; var temp3 = edopt3.childNodes[0].nodeValue; var temp4 = edopt4.childNodes[0].nodeValue; var temp5 = edopt5.childNodes[0].nodeValue; } This is an example of our XML: <ed> <appid>Administrator</appid> <formid>ED009</formid> <question id="1"> <sentence id="1">[email protected]</sentence> <sentence id="2">[email protected]</sentence> <item id="0" answer="f" value="0">0</item> <item id="1" answer="f" value="1">1</item> <item id="2" answer="f" value="2">2</item> <item id="3" answer="t" value="3">3</item> <item id="4" answer="f" value="4">4</item> </question> <question id="2"> <sentence id="1">Beausdene 13</sentence> <sentence id="2">Beauscene 83</sentence> <item id="0" answer="f" value="0">0</item> <item id="1" answer="f" value="1">1</item> <item id="2" answer="t" value="2">2</item> <item id="3" answer="f" value="3">3</item> <item id="4" answer="f" value="4">4</item> </question> </ed> The error I receive intermittently is that "questionXML" is null or not an object. Specifically this line when I call on the submitAns1() method: questionXML = assessnode.getElementsByTagName("question")[edStage]; This solution works on FF, Opera, Chrome & Safari without any issues as far as I am aware. Am I accessing the XML nodes incorrectly? I've been toying with fixes for this bug for weeks now, I'd really appreciate any insight into what I'm doing wrong. On a side note, this is a personal project of mine - it's not university related - I'm much too old for that! Any help greatly appreciated. Regards, Sykth.

    Read the article

  • parentNode.parentNode.rowindex to delete a row in a dynamic table

    - by billy85
    I am creating my rows dynamically when the user clicks on "Ajouter". <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> function getXhr(){ var xhr = null; if(window.XMLHttpRequest) // Firefox and others xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // Internet Explorer try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { // XMLHttpRequest not supported by your browser alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); xhr = false; } return xhr } /** * method called when the user clicks on the button */ function go(){ var xhr = getXhr() // We defined what we gonna do with the response xhr.onreadystatechange = function(){ // We do somthing once the server's response is OK if(xhr.readyState == 4 && xhr.status == 200){ //alert(xhr.responseText); var body = document.getElementsByTagName("body")[0]; // Retrieve <table> ID and create a <tbody> element var tbl = document.getElementById("table"); var tblBody = document.createElement("tbody"); var row = document.createElement("tr"); // Create <td> elements and a text node, make the text // node the contents of the <td>, and put the <td> at // the end of the table row var cell_1 = document.createElement("td"); var cell_2 = document.createElement("td"); var cell_3 = document.createElement("td"); var cell_4 = document.createElement("td"); // Create the first cell which is a text zone var cell1=document.createElement("input"); cell1.type="text"; cell1.name="fname"; cell1.size="20"; cell1.maxlength="50"; cell_1.appendChild(cell1); // Create the second cell which is a text area var cell2=document.createElement("textarea"); cell2.name="fdescription"; cell2.rows="2"; cell2.cols="30"; cell_2.appendChild(cell2); var cell3 = document.createElement("div"); cell3.innerHTML=xhr.responseText; cell_3.appendChild(cell3); // Create the fourth cell which is a href var cell4 = document.createElement("a"); cell4.appendChild(document.createTextNode("[Delete]")); cell4.setAttribute("href","javascrit:deleteRow();"); cell_4.appendChild(cell4); // add cells to the row row.appendChild(cell_1); row.appendChild(cell_2); row.appendChild(cell_3); row.appendChild(cell_4); // add the row to the end of the table body tblBody.appendChild(row); // put the <tbody> in the <table> tbl.appendChild(tblBody); // appends <table> into <body> body.appendChild(tbl); // sets the border attribute of tbl to 2; tbl.setAttribute("border", "1"); } } xhr.open("GET","fstatus.php",true); xhr.send(null); } </head> <body > <h1> Create an Item </h1> <form method="post"> <table align="center" border = "2" cellspacing ="0" cellpadding="3" id="table"> <tr><td><b>Functionality Name:</b></td> <td><b>Description:</b></td> <td><b>Status:</b></td> <td><input type="button" Name= "Ajouter" Value="Ajouter" onclick="go()"></td></tr> </table> </form> </body> </html> Now, I would like to use the href [Delete] to delete one particular row. I wrote this: <script type="text/javascript"> function deleteRow(r){ var i=r.parentNode.parentNode.rowIndex; document.getElementById('table').deleteRow(i); } </script> When I change the first code like this: cell4.setAttribute("href","javascrit:deleteRow(this);"); I got an error: The page cannot be displayed. I am redirected to a new pagewhich can not be displayed. How could I delete my row by using the function deleteRow(r)? table is the id of my table Thanks. Billy85

    Read the article

  • Javascript: Can't control parent of descendant nodes.

    - by .phjasper
    I'm creating elements (level 1) dynamically which in turn create elements (level 2) themselves. However, the children of level 2 elements have "body" as their parent. In the HTML code below, the content if spotAd2 is created by my function createNode(). It's a Google Ad Sense tag. However, the Google Ad Sense tag create elements that went directly under "body". I need them to by under spotAd2. function createNode( t, // type. tn, // if type is element, tag name. a, // if type is element, attributes. v, // node value or text content p, // parent f ) // whether to make dist the first child or not. { n = null; switch( t ) { case "element": n = document.createElement( tn ); if( a ) { for( k in a ) { n.setAttribute( k, a[ k ] ); } } break; case "text": case "cdata_section": case "comment": n = document.createTextNode(v); break; } if ( p ) { if( f ) { p.insertBefore( n, p.firstChild ); } else { p.appendChild( n ); } } return n; } spotAd2 = document.getElementById("spotAd2"); n1 = createNode("element", "div", {"id":"tnDiv1"}, "\n" , null, true); n2 = createNode("element", "script", {"type":"text\/javascript"}, "\n" , n1, false); n3 = createNode("comment", "", null, "\n" + "google_ad_client = \"pub-0321943928525350\";\n" + "/* 728x90 (main top) */\n" + "google_ad_slot = \"2783893649\";\n" + "google_ad_width = 728;\n" + "google_ad_height = 90;\n" + "//\n" , n2, false); n4 = createNode("element", "script", {"type":"text\/javascript","src":"http:\/\/pagead2.googlesyndication.com\/pagead\/show_ads.js"}, "\n" , n1, false); --- Result: <body> <table cellspacing="2" cellpadding="2" border="1"> <tbody><tr> <td>Oel ngati kemeie</td> <td>Kamakto niwin</td> </tr> <tr> <td>The ad:</td> <td> <div id="spotAd2"> <!-- Created by createNode() --> <div id="tnDiv1"> <script type="text/javascript"> google_ad_client = "pub-0321943928525350"; /* 728x90 (main top) */ google_ad_slot = "2783893649"; google_ad_width = 728; google_ad_height = 90; </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> </div> <!-- Created by createNode() --> </div> </td> </tr> <tr> <td>txopu ra'a tsi, tsamsiyu</td> <td>teyrakup skxawng</td> </tr> </tbody></table> <!-- Created by adsense tag, need these to be under tnDiv1 --> <script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"></script> <script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script> <script>google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);</script> <ins style="border: medium none ; margin: 0pt; padding: 0pt; display: inline-table; height: 90px; position: relative; visibility: visible; width: 728px;"> <ins style="border: medium none ; margin: 0pt; padding: 0pt; display: block; height: 90px; position: relative; visibility: visible; width: 728px;"> <iframe width="728" scrolling="no" height="90" frameborder="0" vspace="0" style="left: 0pt; position: absolute; top: 0pt;" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-0321943928525350&amp;output=html&amp;h=90&amp;slotname=2783893649&amp;w=728&amp;lmt=1273708979&amp;flash=10.0.45&amp;url=http%3A%2F%2Fkenshin.katanatechworks.com%2Ftest%2FadsBrowserSide.php&amp;dt=1273708980294&amp;shv=r20100422&amp;correlator=1273708980298&amp;frm=0&amp;ga_vid=695691836.1273708981&amp;ga_sid=1273708981&amp;ga_hid=1961182006&amp;ga_fc=0&amp;u_tz=480&amp;u_his=2&amp;u_java=1&amp;u_h=1080&amp;u_w=1920&amp;u_ah=1052&amp;u_aw=1920&amp;u_cd=24&amp;u_nplug=5&amp;u_nmime=38&amp;biw=1394&amp;bih=324&amp;fu=0&amp;ifi=1&amp;dtd=955&amp;xpc=Jl67G4xiq6&amp;p=http%3A//kenshin.katanatechworks.com" name="google_ads_frame" marginwidth="0" marginheight="0" id="google_ads_frame1" hspace="0" allowtransparency="true"> </iframe> </ins> </ins> <!-- Created by adsense tag, need these to be under tnDiv1 --> </body>

    Read the article

< Previous Page | 1 2 3 4  | Next Page >