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>
4

3 回答 3

1

使用克隆()

只是为了让你有策略

$('#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);

 }
});
于 2013-07-05T12:59:39.587 回答
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

于 2013-07-05T13:03:37.660 回答
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/

于 2013-07-05T13:08:03.207 回答