Getting a listbox's displayed string?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • harry

    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 getSelectedDesc rs(lst)
    {
    var buf;
    var maxItems = lst.length;

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

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

    return buf;
    }

    any ideas

    thanks


  • Joakim Braun

    #2
    Re: Getting a listbox's displayed string?

    "harry" <spammemothers@ yahoo.co.uk> skrev i meddelandet
    news:RpFxd.3803 $Ar5.2688@text. news.blueyonder .co.uk...[color=blue]
    > Just want to traverse a listbox's (multi select) items & for those that[/color]
    are[color=blue]
    > selected extract the displayed text - something like below -
    >
    > function getSelectedDesc rs(lst)
    > {
    > var buf;
    > var maxItems = lst.length;
    >
    > for (var i=0; i < maxItems; i++)
    > {
    > if (lst.options[i].selected == true)
    > buf+=lst.option s[i].value; // What goes here?
    >
    > if(i<(maxItems-1))
    > buf+=",";
    > }
    >
    > return buf;
    > }
    >
    > any ideas
    >
    > thanks[/color]

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

    function getSelectedDesc rs(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



    Comment

    • RobB

      #3
      Re: Getting a listbox's displayed string?


      harry wrote:[color=blue]
      > Just want to traverse a listbox's (multi select) items & for those[/color]
      that are[color=blue]
      > selected extract the displayed text - something like below -
      >
      > function getSelectedDesc rs(lst)
      > {
      > var buf;
      > var maxItems = lst.length;
      >
      > for (var i=0; i < maxItems; i++)
      > {
      > if (lst.options[i].selected == true)
      > buf+=lst.option s[i].value; // What goes[/color]
      here?[color=blue]
      >
      > if(i<(maxItems-1))
      > buf+=",";
      > }
      >
      > return buf;
      > }
      >
      > any ideas
      >
      > thanks[/color]

      [untested]

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

      Comment

      • RobB

        #4
        Re: Getting a listbox's displayed string?


        harry wrote:[color=blue]
        > Just want to traverse a listbox's (multi select) items & for those[/color]
        that are[color=blue]
        > selected extract the displayed text - something like below -
        >
        > function getSelectedDesc rs(lst)
        > {
        > var buf;
        > var maxItems = lst.length;
        >
        > for (var i=0; i < maxItems; i++)
        > {
        > if (lst.options[i].selected == true)
        > buf+=lst.option s[i].value; // What goes[/color]
        here?[color=blue]
        >
        > if(i<(maxItems-1))
        > buf+=",";
        > }
        >
        > return buf;
        > }
        >
        > any ideas
        >
        > thanks[/color]

        [untested]

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

        Comment

        • Mick White

          #5
          Re: Getting a listbox's displayed string?

          harry wrote:
          [color=blue]
          > Just want to traverse a listbox's (multi select) items & for those that are
          > selected extract the displayed text - something like below -
          >
          > function getSelectedDesc rs(lst)
          > {
          > var buf;
          > var maxItems = lst.length;
          >
          > for (var i=0; i < maxItems; i++)
          > {
          > if (lst.options[i].selected == true)
          > buf+=lst.option s[i].value; // What goes here?
          >
          > if(i<(maxItems-1))
          > buf+=",";
          > }
          >
          > return buf;
          > }
          >[/color]

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

          Mick

          Comment

          • RobB

            #6
            Re: Getting a listbox's displayed string?

            Mick White wrote:[color=blue]
            > harry wrote:
            >[color=green]
            > > Just want to traverse a listbox's (multi select) items & for those[/color][/color]
            that are[color=blue][color=green]
            > > selected extract the displayed text - something like below -
            > >
            > > function getSelectedDesc rs(lst)
            > > {
            > > var buf;
            > > var maxItems = lst.length;
            > >
            > > for (var i=0; i < maxItems; i++)
            > > {
            > > if (lst.options[i].selected == true)
            > > buf+=lst.option s[i].value; // What goes[/color][/color]
            here?[color=blue][color=green]
            > >
            > > if(i<(maxItems-1))
            > > buf+=",";
            > > }
            > >
            > > return buf;
            > > }
            > >[/color]
            >
            > function getSelectedDesc rs(lst) {
            > var buf=[],maxItems = lst.length;
            > for(var i=0;i<maxItems; i++) {
            > if(lst.options[i].selected) {
            > buf.push(lst.op tions[i].value);
            > }
            > }
            > return buf.join(",");
            > }
            >
            > Mick[/color]

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

            Comment

            • Fred Oz

              #7
              Re: Getting a listbox's displayed string?

              RobB wrote:
              [...][color=blue]
              > Why create an array, then join it, just to build a string? Seems like
              > showing-off...
              >[/color]

              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

              Comment

              • RobB

                #8
                Re: Getting a listbox's displayed string?

                Fred Oz wrote:[color=blue]
                > RobB wrote:
                > [...][color=green]
                > > Why create an array, then join it, just to build a string? Seems[/color][/color]
                like[color=blue][color=green]
                > > showing-off...
                > >[/color]
                >
                > Creating an array then joining it is usually faster than appending[/color]
                to a[color=blue]
                > 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[/color]
                depending[color=blue]
                > on browser and platform.[/color]

                More than just likely: Internet Explorer concatenates strings much,
                much faster than mozilla-based browsers.
                [color=blue]
                > The good part of using an array is that no logic is needed for when[/color]
                to[color=blue]
                > add a delimiter. When concatenating, you either have to skip the[/color]
                first[color=blue]
                > one if prepending or trim the last (as you've done with replace())[/color]
                if[color=blue]
                > appending.[/color]

                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.
                [color=blue]
                > Getting rid of replace() removes about a quarter of the time
                > difference (and leaves a trailing ", " of course :-) ).[/color]

                Too tired to benchmark that. ~:<
                [color=blue]
                > So I'd go the array method 'cos it's simpler.[/color]

                Now you lost me. Happy holidays regardless. :D
                [color=blue]
                >
                > --
                > Fred[/color]

                (Rob)

                Comment

                • Fred Oz

                  #9
                  Re: Getting a listbox's displayed string?

                  RobB wrote:[color=blue]
                  > Fred Oz wrote:
                  >[color=green]
                  >>RobB wrote:[/color][/color]
                  [...][color=blue]
                  >
                  > More than just likely: Internet Explorer concatenates strings much,
                  > much faster than mozilla-based browsers.[/color]
                  [...][color=blue]
                  >
                  > Too tired to benchmark that. ~:<
                  >[/color]

                  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.len gth; 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.len gth; i++) {
                  if (lst.options[i].selected)
                  buf.push(lst.op tions[i].text);
                  }
                  return buf.join(',');
                  }

                  </script>

                  and the HTML:

                  <form action="">
                  <select multiple size="5" name="selectIdN ame" 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.selectIdN ame);
                  var t1 = new Date();
                  var z = t1.getTime() - t0.getTime();
                  alert(x + '\nThat took '
                  + z + ' milliseconds.\n '
                  + 'There are '
                  + this.form.selec tIdName.options .length
                  + ' selected items');"
                  value="selStrin g0">
                  <input type="button" onclick="
                  var t0 = new Date();
                  var x = selString1(this .form.selectIdN ame);
                  var t1 = new Date();
                  var z = t1.getTime() - t0.getTime();
                  alert(x + '\nThat took '
                  + z + ' milliseconds.\n '
                  + 'There are ' +
                  this.form.selec tIdName.options .length
                  + ' selected items');"
                  value="selStrin g1">
                  </form>






                  --
                  Fred

                  Comment

                  • Mick White

                    #10
                    Re: Getting a listbox's displayed string?

                    RobB wrote:
                    [color=blue]
                    >
                    > Why create an array, then join it, just to build a string? Seems like
                    > showing-off...
                    >[/color]

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

                    Mick

                    Comment

                    • Mick White

                      #11
                      Re: Getting a listbox's displayed string?

                      Fred Oz wrote:

                      [...][color=blue]
                      >
                      > <script type="text/javascript">
                      > function selString0(lst) {
                      > var buf ='';
                      > for (var i = 0; i < lst.options.len gth; 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.len gth; i++) {
                      > if (lst.options[i].selected)
                      > buf.push(lst.op tions[i].text);
                      > }
                      > return buf.join(',');
                      > }
                      >
                      > </script>
                      >[/color]


                      "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

                      Comment

                      • RobB

                        #12
                        Re: Getting a listbox's displayed string?

                        Fred Oz wrote:

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

                        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.len gth;

                        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. ;)

                        Comment

                        • RobB

                          #13
                          Re: Getting a listbox's displayed string?

                          Used this:

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

                          Comment

                          • Michael Winter

                            #14
                            Re: Getting a listbox's displayed string?

                            On Tue, 21 Dec 2004 18:56:49 +1000, Fred Oz <ozfred@iinet.n et.auau> wrote:

                            [snip]
                            [color=blue]
                            > Ok, so here's a little timer.[/color]

                            [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.

                            Comment

                            • Richard Cornford

                              #15
                              Re: Getting a listbox's displayed string?

                              RobB wrote:
                              <snip>[color=blue]
                              > ... . In those cases I'd go with the one whose meaning
                              > (to others) is clearer. ...[/color]
                              <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.


                              Comment

                              Working...