0

I am studying JavaScript and test a function that I thought could prevent the checkbox from be checked (code sample):

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" charset="utf-8">
var myBox = document.getElementById('bike');
myBox.addEventListener('click', stopCheck, false);

function stopCheck(e){
    e.preventDefault();
}
</script>

<form action="">
<input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>

</body>
</html>

but the code does not work. Probably stopCheck is executed AFTER the checkbox changes the checked state. How to fix it?

serge
  • 13,940
  • 35
  • 121
  • 205

3 Answers3

2

Working DEMO

Your script is not able to find element.

Just move your script after form/before closing body tag.

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
1

may be because when you use document.getElementById ,the Dom tree is not created fully yet. move the script below may helps:

<form action="">
<input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>
<script type="text/javascript" charset="utf-8">
var myBox = document.getElementById('bike');
myBox.addEventListener('click', stopCheck, false);

function stopCheck(e){
    e.preventDefault();
}
</script>
ohmygirl
  • 239
  • 1
  • 5
-1

Use document.getElementsByName which returns an array of the elements with the names, in this case the checkboxes.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<script>
    window.onload = function() {
       var vehicle = document.getElementsByName("vehicle");

        for(var i=0;i<vehicle.length;i++){
            vehicle[i].onclick = function(e) {
                e.preventDefault();
            };
        }



    };

</script>

<form action="">
    <input type="checkbox" name="vehicle" value="Bike" id="bike" >I have a bike<br>
    <input type="checkbox" name="vehicle" value="Car">I have a car
</form>
</body>
</html>
marko
  • 10,684
  • 17
  • 71
  • 92