encountered an unexpected token error while trying to implement the onclick

Here's the code I've been working on:

  const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="${() => console.log('hello world')}">Examine</button></td>
</tr>
`
  );
  return tableBody.innerHTML = products.join('');

I'm stumped by this unexpected token error that keeps pointing to the HTML in my code. It seems like it should be a simple fix, but I can't seem to locate the issue. https://i.sstatic.net/Th7ka.png https://i.sstatic.net/YKI71.png

Answer №1

When using a template literal, it is not possible to substitute a function directly. Instead, the source code of the function will be inserted.

In this scenario, there isn't much benefit in attempting to replace the function within the template literal. It would be more practical to include the function body within an onclick attribute.

  const items = itemArray.map(item =>
`
<tr>
  <td>${item.id}</td>
  <td>${item.category}</td>
  <td>${item.price}</td>
  <td><button onclick="console.log('hello world')">View Item</button></td>
</tr>
`
  );
  return tableContent.innerHTML = items.join('');

Answer №2

I suggest using a clientside templating engine to prevent encountering similar issues. One great option is mustachejs.

Here's a potential fix to consider:

const tableBody = document.getElementById('productsTable');

const productArray = [
  {id: 1, type: 'something', price: 100},
  {id: 2, type: 'samething', price: 120}
];
const products = productArray.map(product =>
`
<tr>
  <td>${product.id}</td>
  <td>${product.type}</td>
  <td>${product.price}</td>
  <td><button onclick="(() => {alert('${product.id} ${product.type}');})()">Examine</button></td>
</tr>
`
  );
tableBody.innerHTML = products.join('');
<table id="productsTable">
</table>

Answer №3

After exploring various options, I ultimately settled on this particular approach, although I must admit that the alternative method was more concise:

const items = itemArray.map(item => {
    const row = document.createElement('tr');
    const cell1 = document.createElement('td');
    const cell2 = document.createElement('td');
    const cell3 = document.createElement('td');
    const cell4 = document.createElement('button');

    cell4.addEventListener('click', () =>
      executeSearch(item.id)
    );

    cell1.appendChild(document.createTextNode(item.id));
    cell2.appendChild(document.createTextNode(item.type));
    cell3.appendChild(document.createTextNode(item.price));
    cell4.appendChild(document.createTextNode('View Details'));
    row.appendChild(cell1);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);

    return tableBody.appendChild(row);
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

Utilizing Vue.js with Electron: Establishing seamless data synchronization between backend and frontend

I am currently developing a Vue-Electron application. Picture a settings page on the frontend where users can adjust various variables. It is crucial for me to ensure that all settings are saved even when the settings page is reloaded. To achieve this, I r ...

Sorry, we encountered a snipcart issue: The public API key was not found. To fix this, please ensure that the attribute data-api-key is

I'm experiencing issues with loading Snipcart correctly. It's able to detect the API key on localhost and display the number of items in the cart, but when deployed to Netlify, it briefly shows the item count before displaying the error message: ...

Verify that the input is zero and then proceed to deactivate the submit button if it is indeed zero in AngularJS

app.controller('HelloController', function($scope) { console.log($scope.input1); console.log($scope.input2); if (($scope.op_option == 4) && ($scope.input2 == 0)) { myForm.$invalid; } }); <form id="calc" method="pos ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

Calculate the unique UV coordinates for a custom Buffer Geometry in THREE.JS

I am currently working on creating a curved wall using a vertices array in three JS. The array contains some base vertices in 2D which represent the bottom vertices of the wall. These vertices include the center, lower, and upper points, making it a two-fa ...

When transferring files to the src/pages directory in Next.js, the custom _app and _document components are not recognized

The documentation for Next.js mentions that the src/pages directory can be used as an alternative to /pages. However, I encountered a problem when moving my custom _app.tsx and _document.tsx files into the src folder, as they were being ignored. If you cr ...

Unable to establish a connection with the browser using Socket.IO Spring server, but it works successfully when connecting with

After developing a Spring Boot Application with a SocketIoServer Endpoint, I encountered an issue where the server worked perfectly when tested in a Node.js client environment, but did not respond in Chrome or Edge browsers (haven't tested others). T ...

JavaScript function to substitute instead of writing

function replaceHTML(a,b) { var x = document.getElementById("canvas_html").contentDocument; x.innerHTML = b; } Although the current function works fine, I would like to update it to directly replace the existing content instead of writing new con ...

Utilize the For Each Statement to iterate over a two-dimensional array row by row, rather than by column

Instead of using nested For-loops, which can slow down with larger amounts of data (where n can reach up to 10k), I have an array arrData(n,2) where n is a variable. My goal is to iterate through this array row by row using the for each statement. Below is ...

Retrieving user input from an angular controller function

I have a $resource object in Angular that looks like this: { _id: '1' items: [ {_id: 'a'}, {_id: 'b'}, {_id: 'c'} ] } My goal is to create a form with a checkbox for each element in the items array. In th ...

When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's a ...

What are the steps to refresh the content in a glightbox slider?

I'm currently utilizing Glightbox to set up a gallery that includes descriptions for images. I have a specific request where I want the button text to update on click. However, when the button is clicked and the lightbox reopens, the text on the butto ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Comparing jQuery Mobile and Sencha Touch: Which is the Best

I'm in the process of developing a mobile or tablet version for my current web application. It will be compatible with devices like the iPad and Xoom (Android). I'm stuck between deciding whether to use jQuery Mobile or Sencha Touch as the JS li ...

Building secure applications with React and Express using private routes

In my experience, I have primarily utilized server-side rendering solutions to transfer data from the server to the client and display it in the browser. One of the key advantages of this approach is the ability to access data and send it to the client wi ...

Is there a way to divide a string and insert something into the new array that is created?

I am facing an issue with adding a new fruit to a string that is converted into an array. Here's the scenario: var fruits = "banana,apple"; In an attempt to add a new fruit to this list, I tried converting it to an array and then using the push meth ...

Click event being set within a template literal

In my current project, I am faced with a challenge of implementing an onClick event within a template string. Although the button is rendering correctly, for some reason, the console log is not showing up when the button is clicked. Essentially, I am proce ...

Utilizing AngularJS: Triggering a controller function from a directive

I am currently working on a project with a model named 'user', which includes a controller called 'login' and a directive called 'userMenu'. My goal is to have the userMenu directive utilize the 'login' controller th ...

When using 'passport.authenticate("google")' on the React client, the redirection process is not working properly

Currently, I am utilizing the Google strategy in Passport. As part of this strategy, the client must send a request to '/google'. After that, passport.authenticate should redirect the client to Google's API to select a user. However, my Reac ...