Home » Php » javascript – Onclick function "is not defined"

javascript – Onclick function "is not defined"

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am fairly new to wordpress and am trying to define and call a function but cannot get it to work.

The following code appears in a php file that is called from the content.php file using get_template_part.

<div onclick="checkAllTopicCheckBoxes()"> </div>

I added the following code to the bottom of the function.php file:

function checkAllTopicCheckBoxes() {
    alert("Hello! I am an alert box!!");
}

When I click the element it returns:

(index):363 Uncaught ReferenceError: checkAllTopicCheckBoxes is not defined.

Can anyone please help me?

How to&Answers:

Using OnClick or similar attributes is very poor practice.

Using Javascript Event Listener is a much better way of doing this.
Registering an event in a modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.

HTML:

<div id="checkAllTopicCheckBoxes"> </div>

Your JavaScript is supposed to look like this:

document.getElementById ("checkAllTopicCheckBoxes").addEventListener ("click", myFunction, false);

function myFunction() {
  alert("Hello! I am an alert box!!");
}

HTML attribute (such as Onclick) should be avoided as it concerns the content/structure and behavior are not well-separated, making a bug harder to find.

Answer:

What you wrote is a Javascript function, it must be surrounded by in HTML code. Have you written your function in something like:

echo('<script>function checkAllTopicCheckBoxes() { alert("Hello! I am an alert box!!");}</script>');

Also, I think WordPress must have some function ready to use to add scripts. Try to have a look on wp_enqueue_script (string $handle, string $src = false, array $deps = array(), string|bool|null $ver = false, bool $in_footer = false);

edit: I just found that question, it may answer yours: How to write a Javascript function inside the functions.php of WordPress?

Answer:

function checkAllTopicCheckBoxes() {
    alert("Hello! I am an alert box!!");
}

must be not in <? ... ?> and must have <script>...</script> wrap, e.g.,

======== sample.php =======
<? 
// php script is here
?>

<script>
function checkAllTopicCheckBoxes() {
  alert("Hello! I am an alert box!!");
}
</script>

or if you want to include js inside php script, you must echo it like this

======== sample.php =======
<? 
// php script is here

echo '<script>';
echo 'function checkAllTopicCheckBoxes() {';
echo '  alert("Hello! I am an alert box!!");';
echo '}';
echo '</script>';

?>

Answer:

I faced the same error like you.

If we use the onclick html attribute, we need to define that onclick function within the same html element (by using tags).

It is best practice to create click event listener using javascript/jquery, than using onclick html attribute.