Arex Speed
Arex Speed

Reputation: 177

Button onclick in function

I'm trying to solve this problem. First step is create a table after clicking on first button. Later the table is creating and one row has another button which should starting another function play() with arguments. For this example I just want to display ready in console but this is undefined. When I call this function by simply console.log outside the function then is working correctly. What is wrong with calling function play by button?

<table class="table">
  <tr>
            <th>Team A</th>
            <th>Team B</th>
            <th></th>
        </tr>
</table>
  <button onclick="create()">Create next Match</button>

const table = document.querySelector('.table');

const teams=[{
  name: 'Real',
  point: 10
},
            {
  name: 'Barca',
  point: 20
}]

function create(){
  table.innerHTML += `
<tr id="r1m1">
            <td id="host">${teams[0].name}</td>
            <td id="guest">${teams[1].name}</td>
            <td id="host_score"></td>
            <td id="guest_score"></td>
            <td><button onclick="play(${teams[0]},${teams[1]})">Play</button></td> 
        </tr>`
}

function play(a,b){
  console.log("ready");
}

console.log(play(teams[0],teams[1]))

Upvotes: 0

Views: 42

Answers (2)

Barmar
Barmar

Reputation: 782693

Don't use template substitution, just refer to the variables in directly in the onclick, just like when you call play() in the top-level code.

function create(){
  table.innerHTML += `
<tr id="r1m1">
    <td id="host">${teams[0].name}</td>
    <td id="guest">${teams[1].name}</td>
    <td id="host_score"></td>
    <td id="guest_score"></td>
    <td><button onclick="play(teams[0],teams[1])">Play</button></td> 
</tr>`
}

Upvotes: 2

Quentin
Quentin

Reputation: 944530

You are mashing strings together, so teams[0] gets converted to [object Object] which not only doesn't contain the data you want, but also isn't syntactically valid JavaScript.

You might be able to manage with onclick="play(teams[0],teams[1])" but scope might trip you up (as teams and play must be globals, which are best avoided in general).

In general, your should use DOM methods like createElement, addEventListener and appendChild instead.

Upvotes: 3

Related Questions