最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create Select Tag from Split String - Stack Overflow

programmeradmin1浏览0评论

How do I split this string:

waterfowl||tvs||guitar||pillow||mouse

...by ||?

Then, I'd like to create a select list like this:

<select name="options" id="options">
  <option value="waterfowl">waterfowl</option>
  <option value="tvs">tvs</option>
  <option value="guitar">guitar</option>
  <option value="pillow">pillow</option>
  <option value="mouse">mouse</option>
</select>

How do I split this string:

waterfowl||tvs||guitar||pillow||mouse

...by ||?

Then, I'd like to create a select list like this:

<select name="options" id="options">
  <option value="waterfowl">waterfowl</option>
  <option value="tvs">tvs</option>
  <option value="guitar">guitar</option>
  <option value="pillow">pillow</option>
  <option value="mouse">mouse</option>
</select>
Share Improve this question edited Nov 30, 2011 at 18:34 user1385191 asked Nov 30, 2011 at 17:50 CybercampbellCybercampbell 2,60611 gold badges50 silver badges76 bronze badges 1
  • 2 can you show us where you are stuck? all you need to do is to loop through your array and create the list – Ibu Commented Nov 30, 2011 at 17:52
Add a ment  | 

6 Answers 6

Reset to default 3
var options = 'waterfowl||tvs||guitar||pillow||mouse';

$( '#someDiv' ).html( '<select name="options" id="options">'
    + options.replace(/(\w+)\|*/g, '<option value="$1">$1</option>')
    + '</select>' );
// Turns a string in to a bo box based on:
// @d      Delimiter to split the string up by
// @so     Select box attributes (adding name="foo" means passing {name:'foo'})
// Result: jQuery object of the new select element, populated with the items
//         from the string
String.prototype.toSelect = function(d,so){
    so = so || {};

    var s = $('<select/>',so),
        items = this.split(d);
    for (var i = 0; i < items.length; i++){
        $('<option/>').val(items[i]).text(items[i]).appendTo(s);
    }
    return s;
}

// an example
// Append the following string to the body of the document
// after it's been converted in to  a <Select> element
$('body').append("waterfowl||tvs||guitar||pillow||mouse".toSelect('||',{
    name: 'select',
    id: 'select'
}));

Version with a bit more flexibility (and jQuery abilities): http://jsfiddle/j6DjR/

Preamble:

I used a <select> element with id and name attributes of "assorted". "options" is a terrible id/name for a form element. Read here for more: http://www.fortybelow.ca/hosted/p-lang-javascript/faq/names/


Code:

No mess, no fuss.

(monElements.testing is the form containing the <select> element)

var monElements =
{
    "testing": document.getElementById("testing"),
    "assorted": document.getElementById("assorted")
},
options = "waterfowl||tvs||guitar||pillow||mouse";

function addOptions (optionList)
{
    var i = 0,
    limit = optionList.length,
    parent = monElements.assorted,
    option;
    for (i;i<limit;i++)
    {
        option = document.createElement(
            "option"
        );
        option.text = optionList[i];
        option.value = optionList[i];
        parent.add(option, null);
    }
}

function createOptions (toSplit)
{
    var optionList = toSplit.split("||");
    addOptions(optionList);
}

createOptions(options);

Working Link (with full code):

http://jsbin./ucajep

Try the following:

var input = 'waterfowl||tvs||guitar||pillow||mouse';
var split = input.split('||');
var select = $('<select name="options" id="options"></select>');
$.each(split, function(index, value) {
  var option = $('<option></option>');
  option.attr('value', value);
  option.text(value);
  select.append(option);
});
$('#idOfContainer').empty().append(select);

Your problem is simple:

  1. Split string, using || as separator.
  2. Loop over the splitted string.
    1. Create a new option element
    2. Set its value and text to the current item
    3. Add the element to containing select element

Here's a simple implementation of it (without using jQuery). I use Array.prototype.forEach and element.textContent (the former being ES5 and latter being non-IE), but it should bring the point across (and they're not hard to shim).

function makeSelect( options, separator ) {
    var select = document.createElement( 'select' ),
        optionElem;

    options.split( separator || '||' ).forEach(function( item ) {

        optionElem = document.createElement( 'option' );

        optionElem.value =
            optionElem.textContent =
                item;

        select.appendChild( optionElem );
    });

    return select;
}

var selectElem = makeSelect( 'waterfowl||tvs||guitar||pillow||mouse' );

You can then manipulate selectElem just like you'd manipulate any other DOM element.

You can split the string into an array, then iterate through the array building an HTML string that you can then append to the DOM:

var str = 'waterfowl||tvs||guitar||pillow||mouse',//the string to be split
    arr = str.split('||'),//the split string, each split stored in an index of an array
    out = '';//our output buffer variable

//iterate through each array index
for (var index; index < arr.length; i++) {

    //add this index to the output buffer
    out += '<option value="' + arr[index] + '">' + arr[index] + '</option>';
}

//add the HTML we've built to the DOM, you can also use `.append(<code>)` instead of `.html(<code>)` but if you are using an ID for your select element then you ant to make sure and replace the HTML
$('#container-element').html('<select name="options" id="options">' + out + '</select>');

Here's a jsfiddle to demonstrate: http://jsfiddle/jasper/eb5Dj/

发布评论

评论列表(0)

  1. 暂无评论