vendredi 4 août 2017

Checkbox Images

I am trying to make a checkbox list form with only images and

I have this code from add an image to a html type input check box or radio :

<html>
<script type="text/javascript">
    //global variables that can be used by ALL the function son this page.
    var inputs;
    var imgFalse = '52 0 ROff.png';
    var imgTrue = '52 0 ROn.png';

    //replace the checkbox with an image and setup events to handle it
    function replaceChecks() {
        //get all the input fields on the page
        inputs = document.getElementsByTagName('input');

        //cycle trough the input fields
        for(var i=0; i<inputs.length; i++) {

            //check if the input is a checkbox
            if(inputs[i].getAttribute('type') == 'checkbox') {

                //create a new image
                var img = document.createElement('img');

                //check if the checkbox is checked
                if(inputs[i].checked) {
                    img.src = imgTrue;
                } else {
                    img.src = imgFalse;
                }

                //set image ID and onclick action
                img.id = 'checkImage'+i;
                //set image
                img.onclick = new Function('checkClick('+i+')');

                //place image in front of the checkbox
                inputs[i].parentNode.insertBefore(img, inputs[i]);

                //hide the checkbox
                inputs[i].style.display='none';
            }
        }
    }

    //change the checkbox status and the replacement image
    function checkClick(i) {
        if(inputs[i].checked) {
            inputs[i].checked = '';
            document.getElementById('checkImage'+i).src=getImageUnchecked(i);
        } else {
            inputs[i].checked = 'checked';
            document.getElementById('checkImage'+i).src=getImageChecked(i);
        }
    }

    function getImageChecked(input) {
        if (input == 0)
            return "http://ift.tt/2wetz6t";
        if (input == 1)
            return "http://ift.tt/2wetz6t";
    }

    function getImageUnchecked(input) {
        if (input == 0)
            return "http://ift.tt/2v4i2rE";
        if (input == 1)
            return "http://ift.tt/2v4i2rE";
    }

    function startImages() {

    }

</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>

But the images only start displaying after the first click. Is there any work around I can do to start from the page load ? I tried with the existing functions but achieved nothing.




Aucun commentaire:

Enregistrer un commentaire