Call JavaScript function with parameter in HTML tag

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts:48

Call JavaScript function with parameter in HTML tag

Hi,
I have the following code:

Code: Select all

<img src="image.png" alt="Image" onclick="test(data)" />

<script>
function test(prm) {
  alert(prm)
  console.log(prm);
}
</script>
When I click on the image, the alert() is not executed, and I get this error in console:

Code: Select all

ReferenceError: data is not defined
How to add the "onclick" in the img tag so the test() function alerts the value "data"?

Admin Posts:805
Hi,
If the argument is a string, you should add it between quotes, like this:

Code: Select all

<img src="image.png" alt="Image" onclick="test('data')" />

Similar Topics