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?

ghghjk
  • 223
  • 4
  • 11

5 Answers5

2

Something like this should work using JQuery:

var selectElement = $('#element');
for (var i = 0; i <= yourVariable; i++) {
    selectElement.append('<option value="' +i +'">' + i + '</option>');
}
mayabelle
  • 9,804
  • 9
  • 36
  • 59
1

DEMO

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));

output

<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>
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

here you go

<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')
Daniel Ward
  • 165
  • 8
0

When that newnumber is generated then you can dynamically create your select element.

$("#element").empty();
for(var i = 0; i <= newnumber; i++){
  $("#element").append("<option value='" + i + "'>" + i + "</option>");
}
AbhinavRanjan
  • 1,638
  • 17
  • 21
0

The following Linq Query should retrieve the value based on the attribute value...

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;
gpmurthy
  • 2,397
  • 19
  • 21