mercredi 30 septembre 2020

JavaScript Graphic Checkbox doesn't show

Second checkbox is supposed to be a graphic checkbox but it's not working properly.

index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Graphic Checkboxes</title>
        <meta name="viewport"
            content="width=device-width initial-scale=1">
    </head>
    <h1>Graphic Checkbox Example</h1>
    <form name="form1">
        <p>
            <input type="checkbox" name="check1" id="check1">
            An ordinary checkbox.  
        </p>
        <p>
            <input type="checkbox" name="check2" id="check2">
            A graphic checkbox, created with unobtrusive JavaScript.  
        </p>
    </form>

    <script src="checkbox.js"></script>
</html>

checkbox.js

function graphicBox(box) {
    // Be unobtrusive.  
    if (!document.getElementById) {
        return;
    }

    // Find the object and its parent.  
    obj = document.getElemementById(box);
    parentobj = obj.parentNode;

    // Hide the regular checkbox.  
    obj.style.display = "none";

    // Create the image element and set its onclick event.  
    img = document.createElement("img");
    img.addEventListener("click", Toggle);
    img.src = "images/unchecked.bmp";

    // Save the checkbox ID within the image ID.  
    img.id = "img" + box;

    // Display the graphic checkbox.  
    parentobj.insertBefore(img, obj);
}

function Toggle(e) {
    if (!e) { 
        var e = window.event;
    }

    // Find the image ID.  
    img = (e.target) ? e.target : e.srcElement;

    // Find the checkbox by remoiving "img" from the image ID.  
    checkid = img.id.substring(3);
    checkbox = document.getElementById(checkid);

    // "click" the checkbox.  
    checkbox.click();

    // Display the right image for the clicked or unclicked state.  
    if (checkbox.checked) {
        file = "images/checked.bmp";
    }
    else {
        file = "images/unchecked.bmp";
    }

    img.src = file;
}

graphicBox("check2");

Pathing: https://i.imgur.com/xQITWQK.png

Result: https://i.imgur.com/x4O1CaD.png

As you can see, the check box does not have graphics.

These are my checkbox graphic images: checked.bmp and unchecked.bmp.

checked.bmp: https://i.imgur.com/HH8ukjZ.png

unchecked.bmp: https://i.imgur.com/dhYKUjX.png




Aucun commentaire:

Enregistrer un commentaire