1

如何根据将包含逗号分隔值数据的变量填充选择框?

例子:

var x = Jenny,John,Stephanie,Marc,Ryan,Jessica

预期结果:

[DROP DOWN BOX]
Jenny
John
Stephanie
Marc
Ryan
Jessica
4

5 回答 5

3

http://jsfiddle.net/fYN7M/

HTML

<select id="myoptions">

</select>

JavaScript

var x = "Jenny,John,Stephanie,Marc,Ryan,Jessica";

var options = x.split(",");

var select = document.getElementById('myoptions');
for(var i=0; i<options.length; i++)
{
  select.options[i] = new Option(options[i], i);  //new Option("Text", "Value")
}
于 2013-01-25T14:50:46.753 回答
1

像这样的东西应该工作:

<select id="DropDownList">

</select>

<script type="text/javascript" language="javascript">
   var x = "Jenny,John,Stephanie,Marc,Ryan,Jessica";
   var splitValues = x.split(",");
   for (var i = 0; i < splitValues.length; i++) {
      var opt = document.createElement("option");

      // Add an Option object to Drop Down/List Box
      document.getElementById("DropDownList").options.add(opt);

      // Assign text and value to Option object
      opt.text = splitValues[i];
      opt.value = splitValues[i];
   }
</script>
于 2013-01-25T14:43:46.653 回答
1

这里有一些纯 javascript 给你:

var x = 'Jenny,John,Stephanie,Marc,Ryan,Jessica';
x = x.split(',');

select = document.createElement('select');

for (var i=0;i<x.length;i++) { 
    var new_option_element = new Option(x[i], x[i]);
    select.appendChild(new_option_element);
}

document.body.appendChild(select);

http://jsfiddle.net/crowjonah/ZwtUF/1/

于 2013-01-25T14:46:26.803 回答
0

JavaScript

var x = 'Jenny,John,Stephanie,Marc,Ryan,Jessica'.split(',');
for (var i=0; i<x.length; i++) {
    document.getElementById("names").options[i] = new Option(x[i], x[i]);
}

HTML

<select id="names"></select>

演示

http://jsfiddle.net/hyA96/

于 2013-01-25T14:42:33.103 回答
0

一个简单的方法是:

function populateWithChildren(parent, childTag, values) {
  if (!parent || !values) {
    // no parent element, or no values, nothing can be done so quit here
    return false;
  } else {
    // this ensures that 'values' is an array:
        // if values is a string, it splits that string (assuming a comma delimiter),
        // and split() returns an array, otherwise:
        // we assume it's already an array and use that.
    values = typeof values === "string" ? values.split(',') : values;
    // iterates through all the values in the 'values' array,
    for (var i = 0, len = values.length; i < len; i++) {
      // creates a new element (as passed in the 'childTag' variable)
      var newElem = document.createElement(childTag),
          text = document.createTextNode(values[i]);
      // appends the textNode to the created element
      newElem.appendChild(text);
      // appends the created-element to the 'parent' node passed to the function
      parent.appendChild(newElem);
    }
  }
}

var parent = document.getElementById('select'),
  x = 'Jenny,John,Stephanie,Marc,Ryan,Jessica';

populateWithChildren(parent, 'option', x);

JS 小提琴演示

于 2013-01-25T14:47:48.140 回答