Create Select Tag from Split String

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>

Answers


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 combo 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.net/j6DjR/


Need Your Help

R: collapse a vector by two elements

r paste collapse n-gram

I have a vector, e.g. sdata = c('a', 'b', 'c', 'd').