user1226560
user1226560

Reputation: 39

Grab number from a div and populate select drop down with the same amount of options

I am trying to populate a select drop down with the same amount of options as a number in a separate div.

For example, if a div has a value of "3" in it, i need to populate the select drop down with 3 options.... e.g.:

<select name="quantity">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

If the number in the div is changed to 6 - then it will populate the select with 6 options.

Any help much appreciated! Thanks.

Upvotes: 1

Views: 204

Answers (3)

adedoy
adedoy

Reputation: 2273

Is this what you want?

http://jsfiddle.net/Sgqjg/

the html is:

<div id="changeMe">9</div>

<select name="quantity" id="populateMe">
</select>

and the script is:

var num = parseInt($("#changeMe").text());
var opt = '';
for(i=1;i<=num;i++){
     opt +=  "<option value='" + i + "'>" + i + "</option>";
}
$("#populateMe").html(opt);

Edit: appending and converting to int the text value of the div in each loop slows the proccess.

Upvotes: 1

karim79
karim79

Reputation: 342695

JS:

var $sel = $("select");

$("input").keyup(function () {
    $sel.empty();
    var howMany = parseInt($(this).val(), 10);
    for (var i = 1; i <= howMany; i++) {
        $sel.append("<option value='" + i + "'>" + i + "</option>");
    }
});​

Highly polished layout:

<select></select>
<input />
​​​​​​​​​​​​​​​​​​​​​​

Demo.

Upvotes: 0

Ali
Ali

Reputation: 267227

Call this code whenever your div is changed. Assuming the id of your div is 'otherDiv' and the id of your dropdown is 'yourSelect'

var count = parseInt ( $("#otherDiv").html() );

var options = "";
for (var x = 1; x<= count; x++)
{ 
   options += "<option>" + x + "</option>";
}

$("#yourSelect").htmml(options);

(This requires jquery)

Upvotes: 0

Related Questions