Kumar
Kumar

Reputation: 3

Handling checkbox status using IF in JavaScript

Im learning PHP and trying to print a message based on checkbox check and uncheck.but im getting only else part when im trying to check checkbox .here is the php code .Let me know where im going wrong.

<html>
    <body>
    <script type="text/javascript">
    function on_callPhp()
    {
        if(this.checked) {
            document.write("<?php echo php_func_c();?>");
        }
        else
        {
            document.write("<?php echo php_func_uc();?>");
        }
    }
    </script>

    <input type="checkbox" name="hit_val" value="hit" onchange="on_callPhp()">

    <?php
    function php_func_c()
    {
        echo "CHECKED";
    }

    function php_func_uc()
    {
        echo "UNCHECKED";
    }
    ?>
    </body>
</html>

Upvotes: 0

Views: 42

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138567

Inline event handlers (onchange="...") cause trouble like this, the same applies to document.write. instead use JS to manipulate the DOM:

  // HTML
 <input type="checkbox" id="hit" />
 <div id="output"></div>

  // JS
  const hit = document.querySelector("#hit");
  const output = document.querySelector("#output");

  hit.addEventListener("change", function() {
     output.textContent = hit.checked ? "Checked" : "Unchecked";
  });

Upvotes: 1

trincot
trincot

Reputation: 351403

Some issues:

  • The name on_callPhp seems to suggest that you think JavaScript will call PHP in that function. But that is not true. When PHP runs, it executes both php_func_c and php_func_uc in order to generate the strings you want to have. When PHP has finished running, the page is rendered in the browser. When the user checks the checkbox, no interaction with PHP is happening any more.

  • this does not refer to the checkbox. You can pass this as function argument instead.

  • Don't use document.write and certainly not in an event handler: in the latter case it will completely wipe out the page contents. Use console.log instead for debugging. Then when you are ready for it, you can do something more useful, like showing some other page content.

Here is the corrected code, although I left the name on_callPhp unchanged. Use a different name:

function on_callPhp(chkbox) // <-- notice the parameter
{
    if(chkbox.checked) { // <-- check the argument, not `this`
        console.log("<?php echo php_func_c();?>");
    }
    else
    {
        console.log("<?php echo php_func_uc();?>");
    }
}

The onchange attribute can pass this to the function:

<input type="checkbox" name="hit_val" value="hit" onchange="on_callPhp(this)">

Upvotes: 1

Related Questions