SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Oct 2012
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Use list to generate select options

    I'd like to extend the issue of using javascript variable in html tag:
    My variable is a comma separated list (such as: "a, b, c, d"). The number of elements is changing. I'd like use the list in a SELECT tag.
    Any idea how to do it?
    Thanks

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by jonativ View Post
    I'd like to extend the issue of using javascript variable in html tag:
    My variable is a comma separated list (such as: "a, b, c, d"). The number of elements is changing. I'd like use the list in a SELECT tag.
    Any idea how to do it?
    Thanks
    First you could split the list, then use that list to generate the select options.

    You can split the list for example with: 'a, b,c, d'.split(/, */)
    which splits it based on the comma followed by 0 or more spaces
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,869
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The following function would take the comma separated list of options and return a complete select list containing those values ready to be added to the web page.

    Code:
    createSelect = function(vals) {
    /* use strict */
    var s, i, v, ln;
    s = document.createElement('select');
    v = vals.split(/, */);
    ln = v.length;
    for (i=0; i < ln; i++) {s.options[i] = new Option(v[i], v[i]);}
    return s;
    }
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •