1

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 "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    }

    function getImageUnchecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
    }

    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.

  • Unless you expect your HTML to have to be parsed as XML at some point (highly unlikely), you can omit the last slashes in your elements (`` can just be ``). Along the same lines, you no longer need to specify `type="text/javascript"` in your script tags. – Scott Marcus Aug 04 '17 at 18:07

2 Answers2

2

you have attached the checkClick() to click event of images but you never actually load the images initially, so for that you will have to call checkClick(i) from for loop.

<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';
                checkClick(i);
            }
        }
    }

    //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 "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    }

    function getImageUnchecked(input) {
        if (input == 0)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        if (input == 1)
            return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
    }

    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>
Dij
  • 9,761
  • 4
  • 18
  • 35
1

You have a tremendous amount of unnecessary code and were setting initial image values to images that don't exist.

Also, your HTML was not valid (the <html> closing tag must be the last thing in the document).

Additionally, you should not use inline HTML event attributes (onclick, etc.) and instead completely separate your JavaScript from your HTML and follow modern, standards-based coding practices.

Also, unless you expect your HTML to have to be parsed as XML at some point (highly unlikely), you can omit the last slashes in your elements (<input ... /> can just be <input ... >). Along the same lines, you no longer need to specify type="text/javascript" in your script tags.

Below is a cleaned up and modernized working version of your code. Note how much less code there actually is (without the comments, it's really very little code) and how much simpler that code is. Please review the comments in the code for details on what is being done and why.

.hidden { display:none; }
<html>
  <head>
    <title>Checkbox and Images</title>
  </head>
  <body>
    <input type="checkbox" id="option1" checked> Test<br>
    <input type="checkbox" id="option2" checked> two<br>
    <button id="btnOutput">Check</button>
  
    <script>
      // You should never make global variables as they can collide with other variables
      // Instead, create a "scope" of your own to work in with an Immediately Invoked
      // function expression (an unnamed function that invokes itself right after being
      // declared)
      (function(){
        // Anything declared inside this function is not accessible outside of it
        
        // Since we know these are the only two image paths needed, we can set them up as
        // variables and completely do away with the extra functions that set them.
        var imgFalse = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
        var imgTrue = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
    
        // Get references to all the DOM elements you will need and then you don't
        // have to scan for them again over and over.
        var btnOutput = document.getElementById("btnOutput");
       
        // .getElementsByTagName() returns a "live node" list that causes the DOM
        // to be re-scanned for the elements everytime you reference the list. 
        // Use .querySelectorAll() for better efficiency and turn the node list that
        // returns into a proper JavaScript array so that .forEach() can be used to
        // iterate the elements later.
        var checkboxes = 
            Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));       
            
        // Set up the click event handling function for the button
        btnOutput.addEventListener("click", function(){
          alert('option 1 is checked? ' + checkboxes[0].checked + 
                'option 2 is checked? ' + checkboxes[1].checked);
        });

        // Loop through the checkboxes array
        checkboxes.forEach(function(checkbox, index){
        
          // No need to test the input type because this array only contains checkboxes
          
          // create a new image
          var img = document.createElement('img');

          // Show the right image based on the checked status of the clicked checkbox
          if(checkbox.checked) {
            img.src = imgTrue;
          } else {
            img.src = imgFalse;
          }

          img.id = 'checkImage' + index;   // set image ID
          img.checked = false;
           
          // Set up image click event handler
          img.addEventListener("click", function(){
            
            // Toggle the checked state of the image.
            // In JavaScript, the "checked" property is boolean. It has values of true and false,
            // not "checked" and "" (those are the values to use in HTML attributes).
            this.checked = !this.checked; 
            
            if(this.checked) {
              img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
            } else {
              img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
            }
           
          });

          // place image just prior to the checkbox in the DOM
          checkbox.parentNode.insertBefore(img, checkbox);

          // Hide the checkbox. Use CSS classes instead of inline styles
          checkbox.classList.add("hidden");
        });  
      })();
    
  </script>
</body>
</html>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71