0

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]))
1
  • 1
    When you substitute an object into a template literal, you get [Object object]. Commented Mar 17, 2020 at 16:31

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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>`
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.