473,695 Members | 1,927 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array function SPLICE doesn't work with Select->OPTIONS array. JavaScript

Hi,
I have had to invent a work-around to get past what looks like a
JavaScript bug, the malfunctioning Perl-like JavaScript array functions
including SPLICE() and UNSHIFT().

I have boiled it down to a very simple test case which can be
cut-n-pasted into a .html file and viewed in a browser:

=============== =============== =============== =============== =============== =

<META HTTP-EQUIV="expires" VALUE="Tue, 23 Jun 1998 01:46:05
GMT"><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"
xml:lang="en-US">
<head>
<title>Weird JavaScript Array Function Malfunction!</title>
<meta name="expires" content="Tue, 23 Jun 1998 01:46:05 GMT" />
<script type="text/javascript">//<![CDATA[

function resort() {
var sortara = new Array;
sortara = document.acefor m.sort.options;
var length = sortara.length;
alert("SortAra length = " + sortara.length)
var selidx = document.acefor m.sort.selected Index;
alert("Selected Index = " + selidx);
var selected = sortara[selidx];
alert("Selected item = " + selected.text);
selected = sortara.splice( selidx, 1); // Remove selected array item.
alert("Selected item = " + selected.text); // Never gets here.
Error.
sortara.unshift (selected); // Insert item at top of array.

}

//]]></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"
/>
</head>
<body bgcolor="#B0CEB E">
<form method="post" action="" enctype="multip art/form-data"
name="aceform">
<center>

<table border="2" cellspacing="2" cellpadding="2" >
<tr><td><center >Sort</td></tr>
<tr><td align="center">
<select name="sort" size="4" onchange="resor t(this)">
<option value="Item1">I tem1</option>
<option value="Item2">I tem2</option>
<option value="Item3">I tem3</option>
<option value="Item4">I tem4</option>
</select></td>
</tr>
</table>
</center><div></div></form>
</body>
</html>
=============== =============== =============== =============== =============

The intent of this script is to move the selected item to the to of the
menu. What could be simpler? Something similar to the Perl one-liner:
unshift(@array, splice(@array, $selectIndex, 1)); # Move SelIdx item
to top.

In a JavaScript console in Firefox 1.0.6 as well as in Opera and
evilnet explorer, I get the error message, "Error: sortara.splice is
not a function". Sortara is valued with
"document.acefo rm.sort.options ", and options is an array.

The first 3 alerts show exactly what they should. The array length
comes out to 4, the selected item shows 3 if I click on the last item,
and the item description matches my selection, "Item3" if I choose the
last one. The final alert is never reached, but instead the JavaScript
terminates and a new error message (above) is written to the JS
console.

The 'Reilly Rhino book, "JavaScript , The Definitive Guide" documents
the select object's OPTIONS property as, "An ARRAY of option objects
...."

I can only find 3 hits on this in Google. Is this a real JavaScript bug
or am I loosing it?

THX,

BrianP

Sep 17 '05 #1
2 5220


BrianP wrote:

var sortara = new Array;
sortara = document.acefor m.sort.options;
var length = sortara.length;
alert("SortAra length = " + sortara.length)
var selidx = document.acefor m.sort.selected Index;
alert("Selected Index = " + selidx);
var selected = sortara[selidx];
alert("Selected item = " + selected.text);
selected = sortara.splice( selidx, 1); // Remove selected array item. In a JavaScript console in Firefox 1.0.6 as well as in Opera and
evilnet explorer, I get the error message, "Error: sortara.splice is
not a function". Sortara is valued with
"document.acefo rm.sort.options ", and options is an array.


You may think that options is an array but DOM collections are usually
not implemented as JavaScript arrays in current browsers. The options
property of a select gives you a DOM collection and while that has a
length property and some properties you can access with a number index
that does not mean the object is an Array object instance implementing
all methods that native Array object instances have.
So the error message tells you that the DOM object you are trying to
call a 'splice' method on does not have that method.

The W3C DOM specification lists
<http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-30606413>
so in a browser following that specification options implements the
HTMLOptionsColl ection interface
<http://www.w3.org/TR/DOM-Level-2-HTML/html.html#HTMLO ptionsCollectio n>
where you have a length property and two methods item and namedItem.
Within ECMAScript implementations of the DOM
<http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html> you can
then use
options[index]
instead of
options.item(in dex)
and
options[name]
instead of
options.namedIt em(name)

But that is all the DOM suggests, nothing requiring or suggesting that
there are any methods native JavaScript arrays implement.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Sep 17 '05 #2
BrianP wrote:
Hi,
I have had to invent a work-around to get past what looks like a
JavaScript bug, the malfunctioning Perl-like JavaScript array functions
including SPLICE() and UNSHIFT().

I have boiled it down to a very simple test case which can be
cut-n-pasted into a .html file and viewed in a browser:

=============== =============== =============== =============== =============== =

<META HTTP-EQUIV="expires" VALUE="Tue, 23 Jun 1998 01:46:05
GMT"><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"
xml:lang="en-US">
<head>
<title>Weird JavaScript Array Function Malfunction!</title>
<meta name="expires" content="Tue, 23 Jun 1998 01:46:05 GMT" />
<script type="text/javascript">//<![CDATA[

function resort() {
var sortara = new Array;
sortara = document.acefor m.sort.options;
var length = sortara.length;
alert("SortAra length = " + sortara.length)
var selidx = document.acefor m.sort.selected Index;
alert("Selected Index = " + selidx);
var selected = sortara[selidx];
alert("Selected item = " + selected.text);
selected = sortara.splice( selidx, 1); // Remove selected array item.
alert("Selected item = " + selected.text); // Never gets here.
Error.
sortara.unshift (selected); // Insert item at top of array.

}

//]]></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"
/>
</head>
<body bgcolor="#B0CEB E">
<form method="post" action="" enctype="multip art/form-data"
name="aceform">
<center>

<table border="2" cellspacing="2" cellpadding="2" >
<tr><td><center >Sort</td></tr>
<tr><td align="center">
<select name="sort" size="4" onchange="resor t(this)">
<option value="Item1">I tem1</option>
<option value="Item2">I tem2</option>
<option value="Item3">I tem3</option>
<option value="Item4">I tem4</option>
</select></td>
</tr>
</table>
</center><div></div></form>
</body>
</html>
=============== =============== =============== =============== =============

The intent of this script is to move the selected item to the to of the
menu. What could be simpler? Something similar to the Perl one-liner:
unshift(@array, splice(@array, $selectIndex, 1)); # Move SelIdx item
to top.

In a JavaScript console in Firefox 1.0.6 as well as in Opera and
evilnet explorer, I get the error message, "Error: sortara.splice is
not a function". Sortara is valued with
"document.acefo rm.sort.options ", and options is an array.

The first 3 alerts show exactly what they should. The array length
comes out to 4, the selected item shows 3 if I click on the last item,
and the item description matches my selection, "Item3" if I choose the
last one. The final alert is never reached, but instead the JavaScript
terminates and a new error message (above) is written to the JS
console.

The 'Reilly Rhino book, "JavaScript , The Definitive Guide" documents
the select object's OPTIONS property as, "An ARRAY of option objects
..."


As Martin said, element collections are not arrays.

If it helps, here's a thread here that shows how to put references to
the options into an array. Once you've done that you can use the array
methods on the array of references then re-build the select using just
the options that are left (or have been added maybe).

<URL:http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/7074abbe73943dc b/2d46c041ee36bc6 0?q=Combining+o bject+arrays&rn um=1&hl=en#2d46 c041ee36bc60>

Just remember that your array will be references to the options, not the
actual options. If you show what you are trying to do with the options,
then maybe more help can be provided.

--
Rob
Sep 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1264
by: tomhath | last post by:
Can someone give an opinion whether this is a dumb approach? I want to generate a list of OPTION elements for s SELECT element, but I can't see any (clean) way to use a template on a list of values (other than building HTML outside of the template, which is what I'm trying to avoid). This is what I came up with. It uses three template files and the .py file. The trick (for lack of a better word) is to nest a template inside of itself....
12
6547
by: Kevin Lyons | last post by:
Hello, I am trying to get my select options (courses) passed correctly from the following URL: http://www.dslextreme.com/users/kevinlyons/selectBoxes.html I am having difficulty getting the courses to pass the correct option value and then be displayed at the following URL: http://www.dslextreme.com/users/kevinlyons/selectResults.html I am passing countries, products, and courses. The first two display
6
2019
by: Christopher Benson-Manica | last post by:
I understand that the options property of a select element is an array of the options displayed by the select element. If that's so, then why can't I sort the array? Rather, I *want* to sort the options = how do I do it? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
0
1006
by: Greg Walker | last post by:
I have a bizarre, but easily tested problem. ANY select option containing HTML encoded characters appear as blank lines for Mac IE 5.2. when the page is served as an ASPX page. The EXACT SAME HTML, when served as either ASP or HTML, appears correctly. Server: DotNet 1.1 on XP Professional Client: Mac OS 10.2.8 IE 5.2.2 To test: cut-paste following to a file under wwwroot (I called mine "t1.html"):
1
1682
by: Leonardo Calado | last post by:
Hi, I have the following problem: I have 4 select fields like; <select id="choice_101" name="choice_101"> <option label="Will not attend" value="Will not attend" selected="selected">Will not attend</option> <option label="First Choice" value="First Choice">First Choice</option> <option label="Second Choice" value="Second Choice">Second
1
12503
by: jason.tadeo | last post by:
I am very new to java script and I am trying to be able to have two select boxes. One that has states and one that has cities. On the change or pick of the state then the cities in my data base are they loaded. I do this using sajax (basically using java script to go back to the server with out a page refresh). Well my problem comes after that when I click on a state and then say I picked the wrong state and clicked on another state in my...
3
6429
by: Beholder | last post by:
I hope that someone can help me with the following: Short background explenation: I have a shrfepoint page (newform.aspx) in a item list. On this page is a lookup column that displays a lookup of all category items in previous items. In the code this results in a select/options list like this: <SELECT TABINDEX=1 NAME="urn:schemas-microsoft-com:office:office#CatLookup"><OPTION
1
1337
by: bafadam | last post by:
I've been wracking my brains trying to figure out how to do this, so I thought I would pop it out here for the experts, since my earlier attempts have ended in failure. I'm trying to retrive a collection of <OPTION>'s from an HTML select list, and then loop through them to make them options in a CheckBoxList in VB. Does anyone have a quick and dirty way to use Javascript to get this information, and then loop through it in VB to populate...
2
1869
by: REG | last post by:
Hi All, Could someone point me in the right direction ... have been searching for days for a code snippit or a tuitorial that will show how to: 1. Load XML data into an Html Page in a way that is compatible with most browsers 2. Using Javascript then search on that data using more then one criteria. For example dropdown list one = tour location; dropdown list two = tour duration; dropdown list three = tour price Thank you in advance ...
19
3299
by: viki1967 | last post by:
Hi there. I have this Function: //Funzione Calcola function calcola(frmObj, id)
0
8568
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8845
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8825
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7660
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6491
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4340
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2272
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.