Replace XML with response from a XMLHttprequest - javascript

EDIT
With all the edits to my question it had grown quite lengthy. So let me try to shorten it up a bit and make it easier to follow.
I am building an XUL application using XULRunner. I have it load a dummy XUL page, and then I am looking to use XMLHttprequest to load everything from my server (local ampps server), using PHP to do all the real work. My PHP is setting the XML Content-Type header, and formatting all the output data as XML.
Here is what the JavaScript function, that handles the XMLHttprequest and the response, currently looks like.
function RequestData()
{
if (window.XMLHttpRequest)
{
var url = 'newmenu.xml';
var request = new XMLHttpRequest();
}
else
{
var url = 'http://localdomain.prog/';
var request = Components.classes['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest);
}
request.onload = function(aEvent)
{
var xmlDoc = aEvent.target.responseXML;
var oldmenu = document.getElementById('menubarwrapper');
oldmenu.parentNode.replaceChild(xmlDoc.documentElement, oldmenu);
};
request.onerror = function(aEvent)
{
window.alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
The RequestData() is called with the window onload event.
My original code looked to do nothing, but as I researched and tested I eventually got XULRunner to put out some errors in the error console. Ultimately it lead to what, I now assume, were working versions but I just didn't know it.
The Error Console was putting out this message (and still is)
Warning: XUL box for window element contained an inline toolbox child, forcing all its children to be wrapped in a block.
In order to find out if my code worked I had to get it into Firefox. Hence the reason for the if (window.XMLHttpRequest), as it allows me to test with both Firefox and XULRunner. I then took the XML that my PHP was generating and made a local file, as Firefox will not allow an XMLHttprequest to load a remote file (even if it is technically local).
The above code does import the XML and replaces the <menubar id="menubarwrapper">...</menubar>. But, in both Firefox and XULRunner the menu disappears. I can see all the elements if use Firebug, but why they are no longer visible is beyond me, and there are no errors in the Firebug console. This is where I am currently stumped.
In-case its of any use, below is a copy of the dummy XUL file I load.
<?xml version="1.0"?>
<?xml-stylesheet href="main.css" type="text/css"?>
<window id="main" title="My App" width="1000" height="800" sizemode="maximized" orient="vertical" persist="screenX screenY width height" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/javascript" src="main.js"/>
<toolbox id="toolboxwrapper">
<menubar id="menubarwrapper">
<menu id="file-menu" label="File" accesskey="F">
<menupopup id="file-popup">
<menuitem label="Refresh" funcname="RefreshWin"/>
<menuitem label="Open Window" funcname="OpenWin" acceltext="Ctrl+O" accesskey="O" />
<menuseparator/>
<menuitem label="Exit" funcname="ExitProg"/>
</menupopup>
</menu>
<menu id="edit-menu" label="Edit" accesskey="E">
<menupopup id="edit-popup">
<menuitem label="Undo"/>
<menuitem label="Redo"/>
</menupopup>
</menu>
</menubar>
</toolbox>
</window>
The XML that my PHP generates is quite lengthy, but basically it is the <menubar> element with all of its child elements, similar to above, but with a lot more <menu> and <menuitem> elements.

Without more information, this is just a guess at what the problem is.
What may be happening is that the XML data which is retrieved from your XMLHttpRequest() is being interpreted as XML/HTML and not XUL. This could result in the behavior which you describe. You can check this by using the DOM Inspector to look at the elements which were inserted with your line:
oldmenu.parentNode.replaceChild(xmlDoc.documentElement, oldmenu);
What you should look for is what Namespace URI shows for those elements. If it is not http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul then the elements are not being treated as XUL.
One way to solve this would be to do:
oldmenu.insertAdjacentHTML("afterend", aEvent.target.responseText);
oldmenu.setAttribute("hidden","true");
//Alternately (if you don't want to keep the placeholder <menubar>):
//oldmenu.parentNode.removeChild(oldmenu);

I got it working but the code is 80+ lines longer than it should ever need to be. I tried every variation of importNode, replaceChild, appendChild, adoptNode, removeChild, ect. I could think of. I am fairly certain I could write a book on how many ways you could handle any given XML element or node.
Here's an example of how absurd the issue was. This will work
function AddNewElem()
{
var menubar = document.getElementById('menubarwrapper');
var menuitem = '<menu id="help-menu" label="Help" accesskey="H" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">';
menuitem += '<menupopup id="help-popup">';
menuitem += '<menuitem id="test-menu" label="Test" acceltext="Ctrl+T" accesskey="T" />';
menuitem += '<menuseparator/>';
menuitem += '<menuitem id="about-menu" label="About" acceltext="Ctrl+A" accesskey="A" />';
menuitem += '</menupopup>';
menuitem += '</menu>';
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(menuitem, 'text/xml').documentElement;
menubar.appendChild(xmlDoc);
}
but this will not
function RequestData()
{
var url = 'newmenu.txt';
var request = new XMLHttpRequest();
request.onload = function(aEvent)
{
var menubar = document.getElementById('menubarwrapper');
var responsetxt = aEvent.target.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(responsetxt, 'text/xml').documentElement;
menubar.appendChild(xmlDoc);
};
request.onerror = function(aEvent)
{
alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
newmenu.txt is just the contents of menuitem in the preceding piece of code. I even went as far as to serialize the xmlDoc back to a string and then parse it again and still wouldn't work. I tried a ton of dumb ideas, and many I knew wouldn't work, on the off chance I might get a clue as to the problem. When you crash Firefox you know you have pushed too hard.
But I digress. So for the sake of others trying to use do a XHR with XULrunner below is what I had to do.
function RequestData()
{
var url = 'http://localdomain.prog/';
var request = Components.classes['#mozilla.org/xmlextras/xmlhttprequest;1'].createInstance(Components.interfaces.nsIXMLHttpRequest);
request.onload = function(aEvent)
{
var xmlDoc = aEvent.target.responseXML;
var toolbar = document.getElementById('toolboxwrapper');
var menubar = document.getElementById('menubarwrapper');
toolbar.removeChild(menubar);
var menubar = document.createElement('menubar');
menubar.setAttribute('id', 'menubarwrapper');
var docfrag = document.createDocumentFragment();
docfrag.appendChild(menubar);
var newmenus = xmlDoc.getElementsByTagName('menu');
var menuslen = newmenus.length;
for (var i = 0; i < menuslen; i++)
{
docfrag = CreateMenu(newmenus[i], docfrag);
}
toolbar.appendChild(docfrag);
};
request.onerror = function(aEvent)
{
window.alert("Error Status: " + aEvent.target.status);
};
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('pageid=menu');
}
function CreateMenu(obj, docfrag)
{
var fragbar = docfrag.getElementById('menubarwrapper');
var menu = document.createElement('menu');
menu = SetMenuAttr(obj, 'id', menu);
menu = SetMenuAttr(obj, 'label', menu);
menu = SetMenuAttr(obj, 'accesskey', menu);
var fragmenu = fragbar.appendChild(menu);
var popup = obj.getElementsByTagName('menupopup')[0];
var menupopup = document.createElement('menupopup');
menupopup = SetMenuAttr(popup, 'id', menupopup);
var fragpopup = fragmenu.appendChild(menupopup);
if (popup.hasChildNodes())
{
var childmenu = popup.childNodes;
var menulen = childmenu.length;
for (var i = 0; i < menulen; i++)
{
if (childmenu[i].nodeName == 'menuitem' || childmenu[i].nodeName == 'menu')
{
if (childmenu[i].nodeName == 'menuitem')
{
var menuitem = CreateMenuitem(childmenu[i]);
}
if (childmenu[i].nodeName == 'menu')
{
var menuitem = CreateMenu(childmenu[i]);
}
fragpopup.appendChild(menuitem);
}
}
}
return docfrag;
}
function CreateMenuitem(obj)
{
var menuitem = document.createElement('menuitem');
menuitem = SetMenuAttr(obj, 'id', menuitem);
menuitem = SetMenuAttr(obj, 'label', menuitem);
menuitem = SetMenuAttr(obj, 'accesskey', menuitem);
menuitem = SetMenuAttr(obj, 'acceltext', menuitem);
menuitem = SetMenuAttr(obj, 'disabled', menuitem);
return menuitem;
}
function SetMenuAttr(obj, attr, newobj)
{
if (obj.hasAttribute(attr))
{
newobj.setAttribute(attr, obj.getAttribute(attr));
}
return newobj;
}
Basically had to retrieve each element and its attributes and make new elements. By far its not the preferred solution. For myself, if I have to write one line of code more than is absolutely necessary, it is wrong. The solution should have been 2 lines.

Related

JavaScript XMLHttpRequest return status 0

I'm pretty new to JavaScript / TypeScript and I was writing this tiny piece of TS code to retreive the HTML from another page on my server and put it on a <div id='container'> tag.
let container = document.getElementById("container") as HTMLDivElement;
let req = new XMLHttpRequest();
function getContent(page: string): string {
let content = "";
const basePath = "content/";
const url = basePath + page;
req.open("GET", url);
req.send();
content = req.responseText;
container.innerHTML = content;
console.log(req.status);
return content;
}
getContent('home');
Now, when I open the page on the browser (I'm using GitHub Pages for hosting) all I get is a blank page and a req.status of 0 in the console.
Of course the file content/home.html exists. I tried both getContent('home') and getContent(home.html) but neither worked.
What am I doing wrong?
Thank you to all.

Ajax Request generates html with potential for subsequent Ajax requests. Secondary requests return [object mouseevent] as opposed to generated value

I have a page that is loaded via php. One of the elements in the page is a <li> that has an onclick event. E.g. <li onclick="dynamiccall('1');">blah</li>. After clicking the element an ajax call is issued and the html output is inserted into the page, the tag looks as follows <li onclick="getubilling('1');">blah</li>.
After clicking the generated element with the onclick function getubilling('1');, an ajax call is sent to a php script. The query parameter in the second function to getubilling is displayed as 1, but upon passing it to the ajax call, it shows up as [object mouseevent]. Why is this happening?
the dynamiccall() function is defined as follows in the ajax.js file included in the page:
function dynamiccall(uid){
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse10(xmlHttp.responseText);
console.log(uid);
var holder = uid;
document.getElementById('orgcinfo').innerHTML = '<ul id="b_action_lst2"><li onclick="getuprofile('+holder+')" name="uprofile">Account Settings</li><li onclick="getubilling('+holder+')" name="billing">Billing</li><li onclick="getuchpass('+holder+')" name="chpass">Change Password</li><li onclick="getuadduser('+holder+')" name="adduser">Add User</li></ul>';
var ullist = document.getElementById('b_action_lst2');
var links = ullist.getElementsByTagName('li');
for(var i=0;i<links.length;i++){
var link = links[i];
if(link.getAttribute('name')=="uprofile"){
link.onclick = getuprofile;
}
if(link.getAttribute('name')=="chpass"){
link.onclick = getuchpass;
}
if(link.getAttribute('name')=="billing"){
link.onclick = getubilling;
}
}
//dothis();
}
}
xmlHttp.open("GET", "ajax.php?&p=anotherreq&uid="+uid+"&n="+Math.random(), true);
xmlHttp.send(null);
}
function getubilling(uid){
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse10(xmlHttp.responseText);
console.log(uid);
var holder = uid;
document.getElementById('orgcinfo').innerHTML = '<ul id="b_action_lst2"><li onclick="getuprofile('+holder+')" name="uprofile">Account Settings</li><li onclick="getubilling('+holder+')" name="billing">Billing</li><li onclick="getuchpass('+holder+')" name="chpass">Change Password</li><li onclick="getuadduser('+holder+')" name="adduser">Add User</li></ul>';
var ullist = document.getElementById('b_action_lst2');
var links = ullist.getElementsByTagName('li');
for(var i=0;i<links.length;i++){
var link = links[i];
if(link.getAttribute('name')=="uprofile"){
link.onclick = getuprofile;
}
if(link.getAttribute('name')=="chpass"){
link.onclick = getuchpass;
}
if(link.getAttribute('name')=="billing"){
link.onclick = getubilling;
}
}
//dothis();
}
}
xmlHttp.open("GET", "ajax.php?&p=gubilling&uid="+uid+"&n="+Math.random(), true);
xmlHttp.send(null);
}
A request is issued to http://www.domain.com/ajax.php?&p=gubilling&uid=1&n=2212.32313
The problem is that the resulting UID variable when rendered in the browser results to [object mouseevent] as opposed to the literal value of 1.
I was following this example the only difference I can see is that the example doesn't provide for
passing a dynamic element to the dynamicEvent function where mine does.
What am I missing? Any advice is appreciated.
I suspect this will be the default param passed into the onclick handler, the event object.
Why don't you use addEventListener for a start, rather than inline?
How does this:
dynamiccall('uniqueid');
Know what uniqueid's value is? where does it get it from? In this case, it's taking the value of the event that occurred. My suggestion would be to change the tag to look like this:
<li onclick="dynamiccall(this);" uniqueid="1">blah</li>
then you can set dynamiccall to:
function getubilling(elem) {
var uid = $(elem).attr('uniqueid');
...

Using window.open, document.open, and document.write to display XML (XML rendering gone)

This is related to another question, but is not a duplicate.
It deals with a proposed solution that I have reached an impasse.
I have the following code that reads an XML, makes changes, opens a window, and writes the XML into the document. The problem is that the content is not rendered as XML.
Any way to set a content type, etc, to have the browser handle the content as XML?
<script>
var wxml;
var xDoc;
var xDevices, xInputs;
var xDevice, xInput;
function fSetXmlAInput(iDevice, iNode, nodeNewVal) {
xInput = xInputs[iNode];
xValue = xInput.getElementsByTagName("value")[0];
// change node value:
// console.log("nodeVal: " + xValue.firstChild.nodeValue);
xValue.firstChild.nodeValue = nodeNewVal;
// console.log("newVal: " + xValue.firstChild.nodeValue);
}
function fSetXmlDevice(iDevice) {
xDevice = xDevices[iDevice];
xInputs = xDevice.getElementsByTagName("input");
fSetXmlAInput(iDevice, 0, "22");
fSetXmlAInput(iDevice, 1, "33");
}
function alternativeLoadXML3() {
// load xml file
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "my_template.xml", false);
xhttp.send();
xDoc = xhttp.responseXML;
xDevices = xDoc.getElementsByTagName("device");
fSetXmlDevice(1);
var xmlText = serializeXmlNode(xDoc);
var newWindow = window.open("my_template.xml", "Test", "width=300,height=300,scrollbars=1,resizable=1");
newWindow.document.open();
newWindow.document.write(xmlText);
newWindow.document.close()
};
</script>
Below the XML as well:
<?xml version="1.0" encoding="utf-8"?>
<myXmlRoot>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
</myXmlRoot>
Any way to force the browser to render content in new window as XML...or does using document.open and document.write mean code is rendered as HTML?
Related: Change XML content using JavaScript, missing refresh
Use dataURI to write xml into new window is very easy.
window.open('data:text/xml,'+encodeURIComponent(xmlText),
"Test", "width=300,height=300,scrollbars=1,resizable=1");
Both document.open and document.write are used to write HTML or Javascript to a document. This goes back to the DOM Level 2 Specification of document.open, which assumes that the document is opened in order to write unparsed HTML.
Instead of using document.open and document.write, I would instead suggest dymanically adding elements using the XML DOM as in sampleElement.appendChild(XMLnode)
A similar question can also be found here: how to display xml in javascript?

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

InnerHtml problem in Internet Explorer

I am having problem with applying ajax on IE.I am applying innerHtml on select tag but it is not working my ajax code is
function AjaxF(ftype, cid) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = httpxml.responseText;
if (ftype == 'Files') {
document.getElementById('temp_thumbnail').innerHTML = myarray;
document.getElementById('temp_mainfiles').innerHTML = myarray;
document.getElementById('temp_preview').innerHTML = myarray;
document.getElementById('temp_image').innerHTML = myarray;
}
else {
document.getElementById('temp_thumbnail').innerHTML = myarray;
document.getElementById('temp_main').innerHTML = myarray;
document.getElementById('temp_image').innerHTML = myarray;
}
}
}
var url = "ajax/files_ajax.php";
url = url + "?filetype=" + ftype + "&customerid=" + cid;
url = url + "&sid=" + Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET", url, true);
httpxml.send(null);
}
My php code for creating option is.I am getting the values in filetype and it is working fine on other browsers
$sql="select name ,id from temporary_upload where type ='$filetype' AND customer_id='$customer_id'";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result))
{
$s.="<option id='' name='' selected='selected' value='". $rows['name'] ."'>". $rows['name'] ."</option>";
}
echo $s;
My html for this code is
<select id="temp_thumbnail" name="temp_thumbnail" style="width:452px">
<option></option>
</select>
I have searched for this error on many forums.They all are saying that innerHtml with select has error in IE can anyone help me to resolve this issue.That I can populate my select option.
Thanks in advance
some years ago, i had a similar problem with IE6. if i remember right, i solved this by replacing the whole select-element instead of just replacing the innerHTML (the option-elements).
to do this, you'll have to change the file called via ajax to output the start- and end-tag of your select-element, too. put the select-elemet on your html-site into another element with an id (if there isn't already one you havn't posted) and replace the innerHTML of that outer element.
EDIT: the link gnur posted describes exactly this workaround, so it seems like i remember right ;)
Not a fan of the solutions where they want you to remove the select and than add it back. Kills all the event handlers. Wrote a little function that tries to set the innerHTML. If setting the innerHTML results in no options being added, it rewrites the function so it will create an element and clone its options.
function addOptionsToSelect( selectId, optStr){
var sel = document.getElementById(selectId)
sel.options.length = 0;
sel.innerHTML = optStr;
if(sel.options.length===0){
(addOptionsToSelect = function( selectId, optStr){
var div = document.createElement("div");
div.innerHTML = "<select>" + optStr + "</select>";
var newSelect = div.getElementsByTagName("select")[0];
var sel = document.getElementById(selectId);
sel.options.length = 0;
for(var i=0;i<newSelect.options.length;i++){
var cpy = newSelect.options[i].cloneNode(true);
sel.appendChild(cpy);
}
div = newSelect = sel = null;
})
( selectId, optStr);
}
}
Running Example
This may work for you in IE and FF, of course a bit of modification depending on how and where you want to place the new options in the select ...
function addmore(){
var select=document.getElementById('myselect');
var theindex=select.options[select.selectedIndex];
var option=document.createElement('option');
option.text='text_4';
option.value='value_4';
try{
select.add(option,theindex);
}
catch(e){
//and for ie
select.add(option,select.selectedIndex);
}
}
This page has an excellent work around:

Categories

Resources