471,316 Members | 1,532 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,316 software developers and data experts.

Getting a listbox's displayed string?

Just want to traverse a listbox's (multi select) items & for those that are
selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?

if(i<(maxItems-1))
buf+=",";
}

return buf;
}

any ideas

thanks
Jul 23 '05 #1
19 1716
"harry" <sp***********@yahoo.co.uk> skrev i meddelandet
news:Rp*****************@text.news.blueyonder.co.u k...
Just want to traverse a listbox's (multi select) items & for those that are selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?

if(i<(maxItems-1))
buf+=",";
}

return buf;
}

any ideas

thanks


You want the .text property of the option. But why not return an array
instead?

function getSelectedDescrs(lst)
{
var buf = new Array();
var arrIndex = 0;

for (var i=0, max = lst.length; i < max; i++)
{
if (lst.options[i].selected == true)
buf[arrIndex++] = lst.options[i].text;
}

return buf;
// (return buf.join(","); would give you the exact result as your
original code. But what if the values happen to contain "," characters?)
}

Joakim Braun

Jul 23 '05 #2

harry wrote:
Just want to traverse a listbox's (multi select) items & for those that are selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?
if(i<(maxItems-1))
buf+=",";
}

return buf;
}

any ideas

thanks


[untested]

function getSelectedDescrs(lst)
{
var o,
buf = '',
maxItems = lst.options.length;
for (var i = 0; i < maxItems; i++)
{
if ((o = lst.options[i]).selected)
buf += o.text + ', ';
}
return buf.replace(/,$/, '');
}

Jul 23 '05 #3

harry wrote:
Just want to traverse a listbox's (multi select) items & for those that are selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?
if(i<(maxItems-1))
buf+=",";
}

return buf;
}

any ideas

thanks


[untested]

function getSelectedDescrs(lst)
{
var o,
buf = '',
maxItems = lst.options.length;
for (var i = 0; i < maxItems; i++)
{
if ((o = lst.options[i]).selected)
buf += o.text + ', ';
}
return buf.replace(/,$/, '');
}

Jul 23 '05 #4
harry wrote:
Just want to traverse a listbox's (multi select) items & for those that are
selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?

if(i<(maxItems-1))
buf+=",";
}

return buf;
}


function getSelectedDescrs(lst) {
var buf=[],maxItems = lst.length;
for(var i=0;i<maxItems;i++) {
if(lst.options[i].selected) {
buf.push(lst.options[i].value);
}
}
return buf.join(",");
}

Mick
Jul 23 '05 #5
Mick White wrote:
harry wrote:
Just want to traverse a listbox's (multi select) items & for those that are selected extract the displayed text - something like below -

function getSelectedDescrs(lst)
{
var buf;
var maxItems = lst.length;

for (var i=0; i < maxItems; i++)
{
if (lst.options[i].selected == true)
buf+=lst.options[i].value; // What goes here?
if(i<(maxItems-1))
buf+=",";
}

return buf;
}


function getSelectedDescrs(lst) {
var buf=[],maxItems = lst.length;
for(var i=0;i<maxItems;i++) {
if(lst.options[i].selected) {
buf.push(lst.options[i].value);
}
}
return buf.join(",");
}

Mick


Why create an array, then join it, just to build a string? Seems like
showing-off...

Jul 23 '05 #6
RobB wrote:
[...]
Why create an array, then join it, just to build a string? Seems like
showing-off...


Creating an array then joining it is usually faster than appending to a
string. In this case, about 25% faster. But even my aging machine
gets through 100 selected options in less than 40 ms, so which is
"better" is moot. It is also likely that performance varies depending
on browser and platform.

The good part of using an array is that no logic is needed for when to
add a delimiter. When concatenating, you either have to skip the first
one if prepending or trim the last (as you've done with replace()) if
appending.

Getting rid of replace() removes about a quarter of the time
difference (and leaves a trailing ", " of course :-) ).

So I'd go the array method 'cos it's simpler.

--
Fred
Jul 23 '05 #7
Fred Oz wrote:
RobB wrote:
[...]
Why create an array, then join it, just to build a string? Seems like showing-off...

Creating an array then joining it is usually faster than appending

to a string. In this case, about 25% faster. But even my aging machine
gets through 100 selected options in less than 40 ms, so which is
"better" is moot. It is also likely that performance varies depending on browser and platform.
More than just likely: Internet Explorer concatenates strings much,
much faster than mozilla-based browsers.
The good part of using an array is that no logic is needed for when to add a delimiter. When concatenating, you either have to skip the first one if prepending or trim the last (as you've done with replace()) if appending.
No 'logic' needed to unconditionally trim the end; but how about the
logic of populating a temporary array with strings so it can be
serialized? Works, and is arguably clever for some applications, but I
still don't see the need here.
Getting rid of replace() removes about a quarter of the time
difference (and leaves a trailing ", " of course :-) ).
Too tired to benchmark that. ~:<
So I'd go the array method 'cos it's simpler.
Now you lost me. Happy holidays regardless. :D

--
Fred


(Rob)

Jul 23 '05 #8
RobB wrote:
Fred Oz wrote:
RobB wrote:
[...]
More than just likely: Internet Explorer concatenates strings much,
much faster than mozilla-based browsers. [...]
Too tired to benchmark that. ~:<


Ok, so here's a little timer. I'm not near a Windows box for the time
being so can't do IE myself. I once tested innerHTML versus DOM and
found innerHTML much faster in IE and Firefox, but way, way slower in
Safari - so I'm very much aware that browser/platform combinations are
important when speed is an issue.

<script type="text/javascript">
function selString0(lst) {
var buf ='';
for (var i = 0; i < lst.options.length; i++) {
if (lst.options[i].selected)
buf += lst.options[i].text + ',';
}
// comment out the replace bit to see it's effect
return buf.replace(/,$/, '');
}

function selString1(lst) {
var buf =[];
for (var i = 0; i < lst.options.length; i++) {
if (lst.options[i].selected)
buf.push(lst.options[i].text);
}
return buf.join(',');
}

</script>

and the HTML:

<form action="">
<select multiple size="5" name="selectIdName" id="formID">

<!-- copy 'n paste the options 'til there's 100 or so at least -->

<option value="value1" selected>value1</option>
<option value="value2" selected>value2</option>
<option value="value3" selected>value3</option>

</select>
<input type="button" onclick="
var t0 = new Date();
var x = selString0(this.form.selectIdName);
var t1 = new Date();
var z = t1.getTime() - t0.getTime();
alert(x + '\nThat took '
+ z + ' milliseconds.\n'
+ 'There are '
+ this.form.selectIdName.options.length
+ ' selected items');"
value="selString0">
<input type="button" onclick="
var t0 = new Date();
var x = selString1(this.form.selectIdName);
var t1 = new Date();
var z = t1.getTime() - t0.getTime();
alert(x + '\nThat took '
+ z + ' milliseconds.\n'
+ 'There are ' +
this.form.selectIdName.options.length
+ ' selected items');"
value="selString1">
</form>


--
Fred
Jul 23 '05 #9
RobB wrote:

Why create an array, then join it, just to build a string? Seems like
showing-off...


Yes, it is [showing off], Rob. But more importantly, it demonstrates the
principle: "There are more ways than one to skin a cat"

Mick
Jul 23 '05 #10
Fred Oz wrote:

[...]

<script type="text/javascript">
function selString0(lst) {
var buf ='';
for (var i = 0; i < lst.options.length; i++) {
if (lst.options[i].selected)
buf += lst.options[i].text + ',';
}
// comment out the replace bit to see it's effect
return buf.replace(/,$/, '');
}

function selString1(lst) {
var buf =[];
for (var i = 0; i < lst.options.length; i++) {
if (lst.options[i].selected)
buf.push(lst.options[i].text);
}
return buf.join(',');
}

</script>


http://www.mickweb.com/demos/pushOrConcatanate.html
"selString1()" performs much faster, from 30-50% (safari), 20-35% Moz
1.7.3 (Mac)
[180 length]
Both scripts performances suffer from having to look up the options
length during each iteration.

Mick
Jul 23 '05 #11
Fred Oz wrote:

(snip)
Ok, so here's a little timer. I'm not near a Windows box for the time being so can't do IE myself. I once tested innerHTML versus DOM and found innerHTML much faster in IE and Firefox, but way, way slower in Safari - so I'm very much aware that browser/platform combinations are important when speed is an issue.


Only one problem: that's not the function I supplied. You left out:

if ((o = lst.options[i]).selected) //one lookup instead of two
maxItems = lst.options.length;

Using your benchmarker, I got consistently faster performance from
mine. Overall, the differences were pretty anomalous. In those cases
I'd go with the one whose meaning (to others) is clearer. Cat skinners
may differ. ;)

Jul 23 '05 #12
Used this:

function getSelTxt(obj)
{
var o,
i = 0,
s = '';
while (o = obj.options[i++])
if (o.selected)
s += o.text + ',';
return s.replace(/,$/, '');
}

Jul 23 '05 #13
On Tue, 21 Dec 2004 18:56:49 +1000, Fred Oz <oz****@iinet.net.auau> wrote:

[snip]
Ok, so here's a little timer.


[snip]

Even with several hundred elements, the operation is insignificant on my
machine. Generally, you should perform many iterations of a function to
get an indication of the time it takes to execute.

var e = document.forms[0].elements['selectIdName'],
n = 1000,
i, s, t1, t2, x;

i = 0; s = new Date();
for(; i < n; ++i) {
x = selString0(e);
}
t1 = ((new Date()) - s) / n;

i = 0; s = new Date();
for(; i < n; ++i) {
x = selString1(e);
}
t2 = ((new Date()) - s) / n;

On all the browsers I tried (IE 6, Firefox 1.0, Opera 7.54, and NN 4) the
join approach was faster, but only by any significant extent on NN 4.
Incidentally, that was also the fastest. Firefox was by far the slowest.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #14
RobB wrote:
<snip>
... . In those cases I'd go with the one whose meaning
(to others) is clearer. ...

<snip>

Clarity to others is very related to the relative understanding of those
others. Those unfamiliar with Arrays and their - join - method may find
code that employs them less clear than code that does, while individuals
familiar with those aspects of the language will not necessarily
perceive either as less clear. Unless they are not familiar with regular
expressions and the - replace - method of String objects, in which case
joining an Array might be clearer.

I see no value in choosing scripting techniques out of a deference for
the ignorance of others. You cannot hope to accommodate those who know
nothing, so drawing any boundary will be ultimately arbitrary.

It is probably best in the long run to choose techniques on objective
criteria (for which execution speed can be very significant, but not
always), and tackle (cure) ignorance on the part of others with
appropriate technical explanations.

On the other hand there are things that are generally agreed to
contribute towards code clarity for programmers of all levels of
experience. One of those being consistent formal block indentation,
which is sadly lacking form (or inappropriately implemented in) the code
you have been posting to the group (without any good reason given the
level of detail on the subject of formatting newsgroup posts, and any
code they may contain, available through the FAQ).

Richard.
Jul 23 '05 #15
Richard Cornford wrote:
RobB wrote:
<snip>
... . In those cases I'd go with the one whose meaning
(to others) is clearer. ... <snip>

Clarity to others is very related to the relative understanding of

those others. Those unfamiliar with Arrays and their - join - method may find code that employs them less clear than code that does, while individuals familiar with those aspects of the language will not necessarily
perceive either as less clear. Unless they are not familiar with regular expressions and the - replace - method of String objects, in which case joining an Array might be clearer.

I see no value in choosing scripting techniques out of a deference for the ignorance of others. You cannot hope to accommodate those who know nothing, so drawing any boundary will be ultimately arbitrary.

It is probably best in the long run to choose techniques on objective
criteria (for which execution speed can be very significant, but not
always), and tackle (cure) ignorance on the part of others with
appropriate technical explanations.

On the other hand there are things that are generally agreed to
contribute towards code clarity for programmers of all levels of
experience. One of those being consistent formal block indentation,
which is sadly lacking form (or inappropriately implemented in) the code you have been posting to the group (without any good reason given the
level of detail on the subject of formatting newsgroup posts, and any
code they may contain, available through the FAQ).

Richard.


In a word: *googlegroups*. Always been a fanatic about code formatting
for clarity: tabbing blocks, separating ststements, and using
whitespace as deemed useful. I'm also a stickler about variable
declaration, line termination, and other formalities. I can assure you,
the code samples I've posted here have ALL been properly formatted,
substituting single-character indentation for tabs, truncating longer
lines, etc. gg have just as consistently stripped out all evidences of
this. Since I usually post remotely from wherever I happen to be, it's
difficult to escape this fate.

My other comment is simply based on real-world experience, i.e., having
to explain various code excerpts to others - often experienced coders -
simply because I'd elected to compress lines, nest statements, and -
more on-topic - use 'clever' implementations where a more
pseudocode-like approach would have sufficed. Why choose the one that's
*clever* over the one that's *clear* (a judgement call) if there are no
performance benefits? I try not to deal in concepts like the "ignorance
of others" as (isn't it obvious?) I'm largely ignorant myself.

Anyway, this is a losing proposition, sorry I brought it up...I vote
for push/split :D

cheers & felicitations & thanks always for your "square brackets" faq,
I may be the one who popularized it via hundreds of forum links)

Rob

Jul 23 '05 #16
Oops, meant "push/join", sorry.
Bye.

Jul 23 '05 #17
RobB wrote:
Richard Cornford wrote: <snip>
Clarity to others is very related to the relative
understanding of those others. ... <snip> ... . One of those being consistent formal block indentation,

<snip> ... . gg have just as consistently stripped out all
evidences of this. Since I usually post remotely from
wherever I happen to be, it's difficult to escape this fate.
In a plain text medium like Usenet, stripping leading spaces from lines
is unforgivable. It effectively eliminates many potentially useful
possibilities such as ASCII-art diagrams and certainly is going to
represent a negative contribution to general coding standards. It would
represent a move form being the best provider of web-based access to
Usenet to being on a par with the very worst (forum4designers.com). If
they don't get their act together soon (and I am not optimistic) the FAQ
is going to have to strongly recommend that they not be used to post to
the group.
My other comment is simply based on real-world experience,
i.e., having to explain various code excerpts to others -
often experienced coders - simply because I'd elected to
compress lines, nest statements, and - more on-topic - use
'clever' implementations where a more pseudocode-like approach
would have sufficed.
Do you mean experienced coders of javascript or just experienced coders?
There are often calls from experienced coders of, say Java, for
javascript to be written in a style that is closer to their expectations
(indeed ECMAScript 4th edition (if it is ever finalised and released)
appears to be largely pandering to such individuals). However,
javascript is quite a distinct language that presents possibilities that
are inconceivable in many other languages (particularly in its
fundamentally dynamic nature) and its appropriate employment will tend
to be unfamiliar to those with experience in other areas.
Why choose the one that's *clever* over the one that's
*clear* (a judgement call) if there are no performance benefits?
Without any objective benefit there is no point in choosing an obscure
technique or implementation over something more direct, but there are a
host of (maybe potentially only minor) advantages to be gained from
making informed choices of techniques (and even the minor benefits will
add up). As there are plenty of examples where one common technique is
around 10 to 40 times slower than an alternative then it is worth
knowing something about their relative merits. And there are other
considerations not related to performance and efficiency, such as
encapsulation, where techniques that are less than intuitive to even
experienced coders of other languages can completely eliminate the
potential for namespace collisions. Allowing arbitrary scripts to be
combined on a page without any need worry about the possibility of
accidental interactions.
I try not to deal in concepts like the "ignorance of others"
as (isn't it obvious?) I'm largely ignorant myself.
Given the quantity and range of human knowledge, most people will be
ignorant of the vast majority of things. We are all in that position,
but it isn't so important; it is mitigated by learning the relevant
specifics.
Anyway, this is a losing proposition, sorry I brought it up
...I vote for push/split :D
I don't get that.
cheers & felicitations & thanks always for your
"square brackets" faq, I may be the one who popularized
it via hundreds of forum links)


There are already hundreds of forum links (I wrote it in the first place
so I would not have to repeat that explanation on a weekly basis, and I
have not been the only one to take advantage of its existence to save
repeating otherwise long explanations).

Richard.

Jul 23 '05 #18
JRS: In article <11**********************@f14g2000cwb.googlegroups .com>
, dated Tue, 21 Dec 2004 18:07:08, seen in news:comp.lang.javascript,
RobB <fe******@hotmail.com> posted :
I can assure you,
the code samples I've posted here have ALL been properly formatted,
substituting single-character indentation for tabs,


Single-character indentation, for non-trivial code, is often considered
inadequate by a reader.

Two or three spaces are satisfactory, four or more are unnecessary; I
hope that the FAQ will say so.

If space-adjustment is performed by a human, the resulting code should
be re-tested before posting; that's probably not needed if the
conversion is by a pre-constructed program.

It may be practical to get the posting agent to do it; mine has preset
tabs 8 characters apart, and converts (IIRC) tabs to space on posting.
tab 1 3 // that's a test.

Tabs can be manually reset. If that were sticky, or if the number of
spaces were readily selectable, then I'd be able to tab-indent and post
with space-pairs.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #19
JRS: In article <cq*******************@news.demon.co.uk>, dated Wed, 22
Dec 2004 06:45:31, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :

In a plain text medium like Usenet, stripping leading spaces from lines
is unforgivable. It effectively eliminates many potentially useful
possibilities such as ASCII-art diagrams and certainly is going to
represent a negative contribution to general coding standards. It would
represent a move form being the best provider of web-based access to
Usenet to being on a par with the very worst (forum4designers.com). If
they don't get their act together soon (and I am not optimistic) the FAQ
is going to have to strongly recommend that they not be used to post to
the group.

That does not appear to be the only flaw.

I suggest a general, permanent statement of expectations, followed when
necessary by giving current examples.

Expectations :
Full compliance with applicable Usenet header conventions.
Default to user's time & zone in Date: line. Otherwise, default to
GMT, not -0800.
USEFOR-compliant attributions, preferably full (easily edited).
Text re-formatting not to be default, or readily suppressed.

Hopes :
Positive support for correct quoting, signatures, line-length; but
capable of being over-ridden.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #20

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by orahm | last post: by
2 posts views Thread by Peteroid | last post: by
reply views Thread by Paul_Madden via DotNetMonster.com | last post: by
2 posts views Thread by Paul_Madden via DotNetMonster.com | last post: by
14 posts views Thread by Paul_Madden via DotNetMonster.com | last post: by
1 post views Thread by WhiteWizard | last post: by
2 posts views Thread by =?Utf-8?B?U3RlcGhlbiBSaXRjaGll?= | last post: by
reply views Thread by rosydwin | last post: by

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.