Guido Caffa Guido Caffa - 27 days ago 10
jQuery Question

Jquery dont working on localhost

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?

Answer Source

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)