axellle1
axellle1

Reputation: 25

test:62 Uncaught ReferenceError: is not defined at HTMLButtonElement.onclick (test:62)

I would like to be able to transmit in my function values that are not integers but strings.

I do not have any problem with the integers but for the chains, I have a problem of declaration but I do not understand where it comes from ...

<div id="test"></div>
<script>
  var b = "hello";

  var test = document.getElementById('test');
  test.innerHTML += "<button onclick='myFunction("+b+")'>Click me</button> ";

  function myFunction(MyVar) {
    console.log(MyVar);
  }
</script>

Upvotes: 1

Views: 945

Answers (2)

TheUnKnown
TheUnKnown

Reputation: 681

You're already passing a string inside the function, so you don't need to wrap your var inside double quotes:

var b = "hello";

  var test = document.getElementById('test');
  test.innerHTML += "<button onclick='myFunction(b)'>Click me</button>";
  function myFunction(MyVar) {
    console.log(MyVar);
  }
<div id="test"></div>  

Upvotes: 0

Jan
Jan

Reputation: 2249

Fix variants:

test.innerHTML += "<button onclick=myFunction('"+b+"')>Click me</button> ";
test.innerHTML += "<button onclick='myFunction(\""+b+"\")'>Click me</button> ";
test.innerHTML += "<button onclick=\"myFunction('"+b+"')\">Click me</button> ";

etc.

Upvotes: 1

Related Questions