2016-09-21 67 views
0

我有一個腳本運行時在選擇列表選項中顯示一個數字,當用戶檢查一個特定的值時,它將顯示一個數字,指的是他可以支付多少次賬單。防止選擇的X號碼

注意此代碼:

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

+0

顯示HTML也讓人們可以運行你的代碼,並試圖瞭解你不要以爲我want.But打算給出答案。我只是說 –

回答

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


} 
+0

感謝您的回覆,但check_boxes中的限制代碼在選擇超過6個時顯示未定義的值...任何想法? –

+0

看起來我有一個錯字。在我的增加限制中,我有check_boxes而不是checked_boxes。現在編輯。 – Chris

+2

請解釋你的答案。告訴原代碼有什麼問題,以及你是如何修復它的。 – Barmar