0

I was wondering if there was a way of adding numbers to a select determined by a variable.

For example, newnumber = 3; so then populate the select with 3 (including 0)

<select class="element" id="element" name="element">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

Any thoughts?

4

5 回答 5

2

像这样的东西应该使用 JQuery 工作:

var selectElement = $('#element');
for (var i = 0; i <= yourVariable; i++) {
    selectElement.append('<option value="' +i +'">' + i + '</option>');
}
于 2013-10-11T14:44:48.067 回答
1

演示

HTML

<select class="add"></select>

JS

function add_options(x){
    var opt;
    for(var i=0;i<=x;i++){
        opt += '<option value="'+i+'">'+i+'</option>'
    }
    return opt;
}

$('select.add').append(add_options(3));

输出

<select class="add">undefined
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
于 2013-10-11T14:44:15.147 回答
0

干得好

<select id='example-select'>
</select>

function populateSelectByNumber(howmany,id) {
  var select = document.getElementById(id);
  for (var i=0;i<howmany;i++) { 
    select.options[select.options.length] = new Option(i, i);
  }
}
populateSelectByNumber(5,'example-select')
于 2013-10-11T14:47:29.460 回答
0

当生成该新编号时,您可以动态创建您的选择元素。

$("#element").empty();
for(var i = 0; i <= newnumber; i++){
  $("#element").append("<option value='" + i + "'>" + i + "</option>");
}
于 2013-10-11T14:49:08.297 回答
0

以下 Linq 查询应根据属性值检索值...

string input = "<xml string>"
string key = "3";
XElement root = XElement.Parse(input);
var output = (from el in root.Elements("option")
              where (string)el.Attribute("value") == key
              select el).First().Value;
于 2013-10-11T14:49:57.767 回答