Reputation: 1251
I have this code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(':checkbox').change(function(){
var len = $(':checkbox:checked').length;
$(':checkbox').not(':checked').prop('disabled', len >= 2)
});
</script>
</head>
<body>
<input type="checkbox" id="4" name="4[]" value="abc" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="qwe" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="xyz" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="pqr" style="width:10px">
</body>
</html>
this is running in this JSfiddle: http://jsfiddle.net/ESH54/ but i cant make it work in localhost. Any idea?
Upvotes: 0
Views: 90
Reputation: 607
You try moving js code to the bottom of the page. It should be after the html is genarated
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" id="4" name="4[]" value="abc" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="qwe" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="xyz" style="width:10px">
<input type="checkbox" id="4" name="4[]" value="pqr" style="width:10px">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(':checkbox').change(function(){
var len = $(':checkbox:checked').length;
$(':checkbox').not(':checked').prop('disabled', len >= 2)
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 2537
you try to access elements that doesn't exist at this time. You have to wait for the dom to be ready
<script type="text/javascript">
$(function() {
$(':checkbox').change(function(){
var len = $(':checkbox:checked').length;
$(':checkbox').not(':checked').prop('disabled', len >= 2)
});
});
</script>
Also see: https://learn.jquery.com/using-jquery-core/document-ready/
Your jsfiddle works, because the script is wrapped inside the head in the window.onload handler (click at the icon next to "Javascript" to see the configuration / this detail)
Upvotes: 2