开发者

Dynamically instantiating SELECT options via other SELECT selections

Imagine, for a moment

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

As well as another identical select box

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Should I have another select box, Imagine "Volvo" and "Saab" were to be selected in these select boxes, the (third) resulting select box should contain the options 'Volvo' and 'Saab'.

Seems simple right? It gets more complex of course when someone changes their answer, and questions like how I extend this dynamically to any number of select boxes (i.e - Imagine I had more than two select boxe开发者_如何学Pythons) begin to emerge, and in general, the DOM, and maybe jQuery is not as friendly as perhaps it should be when it comes to these sort of things, so I ask your wisdom StackOverflow

What is the most kosher way to retrieve the current values of a set of select boxes and use those dynamically as the options of another select box


If you name your first and second select boxes with the IDs first and second, and the last one third..

// Get our select lists
var first = $("#first");
var second = $("#second");
var third = $("#third");

// Merge the selections from the first and second lists
function mergeSelections() {
    // Get the list elements
    var firstSelections = $("option:selected", first);
    var secondSelections = $("option:selected", second);

    // Clear the destination list
    third.clear();

    // Merge lists, add each selected element
    $.merge(firstSelections, secondSelections).each(function(i, item) {
        // Clone the original, add to the third list
        $(item).clone().appendTo(third);
    });
}

// Set up actions
first.change(mergeSelections);
second.change(mergeSelections);


Try this

$("select:first option");//This will give you options dom element array and you iterate through this and create options for other select element.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜