防止选择

时间:2016-09-21 18:11:40

标签: javascript jquery html

我有一个脚本在选择列表选项中显示一个数字,当用户检查一个特定值时,它会显示一个数字,表示他可以支付账单的次数。

请注意以下代码:

var tabelaParcelas = [2,3,4,6,8,10,12];

$(document).ready(function(){
    update();
});

$('input[type=checkbox]').click(function(){
    update();
})

function update(){
  var list = $('#instNum2'); // use selector only once whenever possible for better performance

  // clear any existing options from the dropdown list
  list.html("")

  // count checked boxes
  var checked_boxes = 0
  $(".check_list").each(function(){
    if(this.checked){
        checked_boxes++;
    }
  });

  // append options to the select list
  for(var i=0;i<checked_boxes;i++){
    var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
        list.append(option);
  }


}

这是对的!但问题是,我还需要显示1x,这就是根本没有显示的内容,1x应该是可见的,无论你选择了多少盒子,等等,当我选择更多超过7个盒子,该选项继续生成空选项,而它应该只显示12x而不添加任何新的...

1 个答案:

答案 0 :(得分:0)

var tabelaParcelas = [2,3,4,6,8,10,12];

$(document).ready(function(){
    update();
});

$('input[type=checkbox]').click(function(){
    update();
})

function update(){
  var list = $('#instNum2'); // use selector only once whenever possible for better performance

  // clear any existing options from the dropdown list
  list.html("")

  // count checked boxes
  var checked_boxes = 0
  $(".check_list").each(function(){
    if(this.checked){
        checked_boxes++;
    }
  });

  //add limit to check_boxes
  //This section was not in original code
  //  Could also do if(checked_boxes > tabelaParcelas.length) {checked_boxes = tabelaParcelas.length;}
  //Would make it more dynamic.
  //This is added to limit the number of options added to the length of the array at the top.  
  //This will prevent blank options from being added as requested in the question.
  if(checked_boxes > 6) {
      checked_boxes = 6;
  }

  //add 1x option to empty list
  //This was not in original code
  //This was added as the list was cleared when this function is run and they always wanted 1x to appear as an option.
  list.append("<option value='1' selected>1</option>");

  // append options to the select list
  for(var i=0;i<checked_boxes;i++){
    var option = $("<option>", {value: tabelaParcelas[i], "text": tabelaParcelas[i]});
        list.append(option);
  }


}