Reputation: 471
I have a form where users can pick several locations they want to stay at and they have to specify the time they are going to be at each location but first, they have to enter how many days in general they are going to be at every location, for instance, if I want to be at two locations 2 days at the first one and 3 at the second one, I have to enter 5 days first and then pick the locations I want to stay at specifying for each location how many days I want to be there. Well the thing is that to prevent the user to enter a wrong number of days for a location I created a select elemento for each location so when the user enters the general number of days I fill up the select elements with that information (options from 1 to day number), that is working just fine, but when the user picks a location and especify a day amount for that location I want the rest of the select elements to be filled with the ramaining days, so I use this code to do that
function fillUpSelects2(start, top, who) {
var optionArray = new Array();
// create the new options
for (var i = 1; i <= top; i++) {
optionArray.push(new Option(i, i));
}
// get all the select elements
var selects = jQuery("select.estanciaselect");
// loop through the selects to change their content
for (var i = 0; i < selects.length; i++) {
// if selects[i] is not the one who triggered the change event
if (selects[i].getAttribute('id') != who) {
// then I erase all its options
selects[i].options.length = 0;
//and here is where it is supposed to add the new options
for (var j = 0; j < optionArray.length; j++) {
selects[i].options[selects[i].options.length] = optionArray[j];
}
}
}
}
well when I run this all the selects end up empty but the last one which gets filled up properlly
Upvotes: 1
Views: 3721
Reputation: 22652
Following is an approach on how to add items to multi-select (though not a direct answer to your question)
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var o = new Option("option text", "value");
$(o).html("option text");
$("#leftValues").append(o);
});
</script>
<select id="leftValues" size="5" multiple></select>
Refer Adding options to a <select> using jQuery? too
Upvotes: 0
Reputation: 50905
If you're using jQuery, you might as well use it to append them:
for (var i = 1; i <= top; i++) {
$(".selects").prepend($("<option>")
.val(i) // Might have to use .attr("value", i) instead
.html(i));
}
Here's a jsFiddle demonstrating two options you could use (including the one above), but there are plenty more:
Upvotes: 1