2016-09-05 78 views
0

我想設置它。所以當它超過一定值時,會發出警報,通知用戶勾選了太多框。警報顯示成功,但相關複選框保持勾選狀態。我以前使用過這個功能,但這次不工作。我不知道爲什麼。預先感謝您提供任何幫助。框檢查即使提示警告?

function cannotDoThreeATTandAwareness() { 
    var i = 0; 
    $('.ATT, #aware').each(function() { 
    if ($(this).is(':not(:visible)')) { 
     i += 3 
    } 
    }); 
    $('.ATT').each(function() { 
    if ($(this).is(':checked')) { 
     i += 3 
    } 
    }); 
    $('.awareness').each(function() { 
    if ($(this).is(':checked')) { 
     i += 1 
    } 
    }); 

    if (i > 9) { 
    alert('You cannot select this paper as you have already selected your Core 2 paper'); 
    }; 

    return i == 10; 
} 
onclick =" if(cannotDoThreeATTandAwareness()){this.checked=false};" 
+0

'i'可能會大於9,但*不* 10 ... – Biffen

+0

'return i> 9;'? '$('。ATT,#aware')'在後面的'$('。ATT,')'背景下沒什麼意義...... –

+0

你能顯示html嗎?你可以寫一個選擇器,包括':selected',然後獲取它的長度以知道檢查了多少。一旦用戶超過限制,您必須手動取消選中最後一個複選框。 – Shilly

回答

0

只需return你想要的單擊事件裏面太結果。

function cannotDoThreeATTandAwareness() { 
 
    var i = 0; 
 
    // used 'true' to always make it fail, for the sake of example 
 
    if (true || i > 9) { 
 
    alert('You cannot select this paper as you have already selected your Core 2 paper'); 
 
    }; 
 

 
    return i > 9; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label> 
 
    <input type="checkbox" onclick="return cannotDoThreeATTandAwareness()"> 
 
    Click me 
 
</label>

另一種選擇是添加一個參數的功能,比方說e,並要的變化,你可以使用e.preventDefault()。爲了使這項工作,你需要傳遞事件到功能,這裏有一個片段:

function cannotDoThreeATTandAwareness(e) { 
    ... 
    if (true || i > 9) { 
    e.preventDefault() 
    ... 
    }; 
} 

<input type="checkbox" onclick="cannotDoThreeATTandAwareness(event)">