Felipe S. Bueno Felipe S. Bueno - 2 months ago 8
Javascript Question

Preventing X numbers from select

I have a script running to show a number in the select list options when the user check one specific value it will display a number refering to how much times he can pay his bill.

Note this code:



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);
}


}


That's correct! But the thing is, I need to display
1x
as well, and that's what's not showing at all,
1x
should be visible always no matter how much boxes you select, and other thing, when I select more than 7 boxes, the option keep producing empty options, while it should only keep displaying
12x
without appending any new...

Answer
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.
  if(checked_boxes > 6) {
      checked_boxes = 6;
  }

  //add 1x option to empty list
  //This was not in original code
  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);
  }


}