Atmega 328
Atmega 328

Reputation: 105

JavaScript function passing value not working properly

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction(demox)">Click me</button>

<p id="demo"></p>

<p id="demox"></p>

<script>
function myFunction(cat) {
var dog = document.getElementById( cat);
dog.innerHTML = "Hello World";
}
</script>

</body>
</html>

I am trying to pass an id value of "demox" to a js function to display some text with an onclick event, but it doesn't seem to work. what is the problem here?

Upvotes: 0

Views: 76

Answers (1)

GibboK
GibboK

Reputation: 73938

You can find script modified which solve your issue here.

https://jsbin.com/yitovikete/edit?html,output

Generally, I would suggest you to add <script> tag within the header of your HTML page like this:

https://jsbin.com/yitovikete/1/edit?html,output

This is good when you need to do something while the body is loading, or want to maybe make some ajax requests.

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction('demox')">Click me</button>

<p id="demo"></p>

<p id="demox"></p>

<script>
function myFunction(cat) {
var dog = document.getElementById( cat);
dog.innerHTML = "Hello World";
}
</script>

</body>
</html>

Upvotes: 3

Related Questions