使用循环填充选择

Populate select with loop

本文关键字:选择 填充 循环      更新时间:2023-09-26

我想在选择更改时重新填充选择框。

到目前为止我所做的(不起作用):

$('select#mnt').change(function(){
     var month = $(this).val();
     var days = new Date(year, month, 0).getDate();
     var toMonth = <?php echo $tomon; ?>;
     var toDay = <?php echo $today; ?>;
     var result='';
     if (month!=toMonth) {
        for(var i=1; i<=days;i++){
            result += '<option>'+i+'</option>';
        }
        $('select#days').empty().html(result);
     }


  });

代码片段中不存在 var year

var days = new Date(year, month, 0).getDate();

它应该是这样的:

var year=2011;//or $('input#year').val();
var days = new Date(year, month, 0).getDate();

该函数中没有 year 变量。你在其他地方创造它吗?

这是一个工作示例,进行了一些更改: 演示

$('select#mnt').change(function(){
 var month = $(this).val();
 var days = new Date(2012, month, 0).getDate();
 var toMonth = 5;
 var toDay = 4;
 var result='';
 if (month!=toMonth) {
    for(var i=1; i<=days;i++){
        result += '<option>'+i+'</option>';
    }
    $('select#days').empty().html(result);
 }
});