2013-07-05 158 views
0

如何添加具有不同ID的选择框的相同数量的选择框,即由另一个选择框值选择的选择框?使用其他选择框的值创建其他选择框

如果选择了选项3,应该创建3个新的选择框。 如果选择了选项2,则应创建2个新的选择框。 ... 我希望你明白。

有人可以帮我吗?万分感谢!

<select name="children" id="children"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
... 
</select> 
<div id="add_select"> 
...and below should be new created with jquery... 

<select name="children" id="child-1-age"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
... 
</select> 

<select name="children" id="child-2-age"> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
... 
</select> 
</div> 
+1

jQuery的克隆是什么ü需要 – bipen

+0

你甚至可以尝试一个循环将循环内构建选择标签直到第一个列表框的计数值为止......这样,您甚至可以考虑在动态创建的列表框中添加唯一的ID' – dreamweiver

+0

设置您的初始选择列表选项的实际'value'属性,然后您可以在for循环中使用该值,并创建其他列表 – tymeJV

回答

0

使用克隆,您可以创建模板并将其复制x次数。我记录我的代码,希望这将是足够的了解:

$('#children').change(function(){ 
    var $div = $('#add_select'), //Select the appending div 
     $select = $('<select/>', {name : 'children'}), //Create a template 
     index = this.selectedIndex; //get the number of select 

    $div.empty(); //Erase old select 

    if(!index) return; //Stop the code if the number of child is 0 

    for(var i=0; i<14; i++){ //Maximum child age 
     var $option = $('<option/>', {text : i, value : i});//Create the option element 
     $select.append($option);//Append to the template 
    } 

    for(var u=0; u<index; u++){//Get the number of child 
     var $clone = $select.clone(); //Clone the template 
     $clone.attr('id', 'child-'+(u+1)+'-age').appendTo($div); //Change its id and append to the container 
    } 
}).trigger('change'); 

这里工作小提琴:http://jsfiddle.net/NCLae/1/

1

使用clone()

只是为了让你strated

$('#children').change(function(){ 
    var $this=$(this); 
    var cloneItem=$(this).val(); 
    for(var i=1;i<=cloneItem;i++){ 
     var clonedItem=$this.clone().find('select').attr('id','child'+i+'-age').end(); 
     $('#add_select').html(clonedItem); 

    } 
}); 

$('#children').change(function(){ 
var $this=$(this); 
var cloneItem=$(this).val(); 
for(var i=1;i<=cloneItem;i++){ 
    var clonedItem=$this.clone(); 
    clonedItem.attr('id','child'+i+'-age'); 
    $('#add_select').html(clonedItem); 

} 
}); 
0

也可以尝试下面的代码:

$('#children').change(function() { 
    var selected = $(this).val(); 
    for (var i = 0; i < selected; i++) { 
     var idd = "add_select-" + selected+ "-age"; 
     $('#children').clone().attr('id', idd).appendTo('body'); 
    } 
}); 

选中此JSFiddle

相关问题