I keep encountering the error message "Uncaught SyntaxError: unexpected token: identifier" and I don

for (post of posts) { //Posts are retrieved from a Python Django function                                         
  let expandContent = '';
  let postDesc = post.fields.description;
  if (post.fields.description.length > 227) {
    expandContent = `<p class="btn btn-link" onclick="this.innerHTML = ${postDesc}">Read more</p>`;
  };
  output += `<p class="card-text" style="white-space: pre-line;">${post.fields.description.substring(0, 227)} ${expandContent}</p>`;

}

However, upon clicking the read more button:

Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22

I attempted to eliminate the onclick and instead add this at the end:

$('#mainPosts').append(output)

function showMore() {
  $('.readMore').click(function(e) {
    e.preventDefault();
    $(this).parent().html(`<br>${post.fields.description}`)
  })
}
let g = document.createElement('script');
let s = document.getElementsByTagName('script')[0]
g.text = showMore();
s.parentNode.insertBefore(g, s)

The issue lies in the fact that it doesn't replace the substring of the current post description with the full one; rather, it replaces it with the complete description of the very last post in the list!

Answer №1

Modify the code from

onclick="this.innerHTML = ${postDesc}
to
onclick="this.innerHTML = '${postDesc}'
.

Let's analyze how the current template string will be interpreted if

postDesc == "hello world"
:

<p class="btn btn-link" onclick="this.innerHTML = hello world"> Read more</p>`;
. When the JavaScript VM attempts to run this.innerHTML = hello world, it identifies hello as an undefined identifier, which is acceptable. However, it then encounters world, another undefined identifier, leading to the error unexpected token: identifier.

As Andreas mentioned, a single quote in postDesc can create issues. Here is a solution for that:

onclick="this.innerHTML = '${postDesc.replace(/([\"\'])/g,'\$1')}'
.

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

Order of Loading WebResources in ScriptControl

As I work on integrating a new control into a project that already contains ASP.Net controls, I am faced with the challenge of managing multiple .Net classes and JavaScript files. Each control consists of a .NET class (inheriting ScriptControl) along with ...

Combining namespaces in Typescript, specifically for ASP.NET Razor project files

Having two different namespaces can be tricky. namespace1: file1.ts ///<reference path="./file2" /> import * as NameSpace2 from './file2'; export namespace namespace1 { export class Class1 { constructor( ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Learn the step-by-step process of converting JSON functionality into HTML/text output using Golang

I need to modify the API responses to display as HTML or text, as the current script only outputs JSON format. func writeJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) { w.Header().Set("Content-Type", "applicatio ...

Creating dynamic divs on button click for my project is something that I must do, and I will

When the user clicks on the Add button, a new div should be added as shown in the image above. Implementing this functionality using Bootstrap is crucial because the divs must rearrange correctly based on different resolutions such as 1920x900, 1280x600, ...

The slice method for copying arrays seems to be malfunctioning

It's perplexing that even after utilizing distances.slice(), I end up modifying the original array when I make changes to the new copy. What could be causing this unexpected behavior? var distances = [ ['-1', '10', '-1&ap ...

In AngularJS, I was attempting to display array indexes in reverse order. Can anyone provide guidance on how to achieve this?

<tr ng-repeat="qualityalert in qualityalerts" current="$parent.start;$parent.start=$parent.start+(qualityalerts.length);"> <td class="v-middle">{{current + $index}}</td> </tr> Important: I was talking about this specific code snipp ...

Enhance your online shopping experience with Woocommerce's advanced add to cart ajax feature

Is there a way to automatically update the mini-cart when a product is added via ajax to the cart? I've found a solution to update the cart quantity using a filter called woocommerce_add_to_cart_fragments. Here's how I implemented it: add_filter ...

Using Drupal 7 to make asynchronous Ajax requests

As a newcomer to the world of Drupal, I am currently working with version 7.x and seeking guidance on how to set up a basic ajax call. Within my template file, there is a button that triggers a javascript function when clicked: <input type='butto ...

PHP fails to return response to jQuery AJAX request

I am encountering issues with my jQuery AJAX requests in PHP. What could be wrong with my simple example? index.php - includes loading JS, PHP files, and defining a button and a paragraph. <html> <head> <script src='jquery ...

Using nested for loops in PHP to insert JSON data into a single row in an SQL table

I am faced with the challenge of inserting 3 different arrays from a JSON file into the same row on my SQL table. Instead of each array being inserted into separate rows, I attempted to use nested for loops in my code. However, I encountered two issues: ...

How to achieve an endless cycle using Promise recursion in a NodeJS environment

I am planning to replace my blocking infinite while loop with promises. My run function is quite simple - it lights up an LED and then turns it off before moving on to the next one. Since Promises do not work inside while loops, I'm exploring how I c ...

What is the best way to identify duplicate IDs within an array?

function fetchTweets($query){ $url = "http://search.twitter.com/search.json?q=".$query."&include_entities=true&result_type=mixed"; $content = file_get_contents($url); $tweetsArray = json_decode($content, true); foreach($tweetsArray ...

Passing a number variable from a function to setInterval using JavaScript

const exerciseItems = [ ["crunches", 30], ["crunches", 45], ["squats", 30], ["squats", 45], ["lunges", 30], ["lunges", 45], ["wall sits", 30], ["wall sits", 45], ["push ups", 30], ["push ups", 45], ["leg ups", 30], ["leg ups ...

Generate Azure ARM Template for Creating KeyVault Secrets in Keyvault across Multiple Resource Groups

For my Azure deployment, the Virtual Machine's Username and Password are automatically created and passed as parameters. The resource group where the VM is deployed can be any. My Keyvault resides in a specific resource group, and I need to store the ...

How can I eliminate the hover effect in the navigation bar?

How can I remove the hover effect from the navigation bar? <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2"> <ul class="nav navbar-nav navbar-right> <li><a href="#">BUSINESS EXCHANGE</a></li> ...

Unable to retrieve data. Issue: Unable to send headers after they have already been sent to the client

Experiencing an error while attempting to retrieve posts from a specific user. The code for fetching the data appears to be correct, so it's unclear where the error is originating from. Error from server side https://i.stack.imgur.com/ep1Xh.png Error ...

Show the correct URL address in the browser's address bar

My website utilizes Jquery/Ajax to dynamically load html pages into a specific div. By clicking on links with a certain class, the content opens up in this designated div, while the URL displayed in the address bar remains www.example.com. This setup allow ...

Filtering MongoDB db.adminCommand ResultsLearn how to effectively filter the output of

Would anyone happen to know a way to effectively filter the output of MongoDB's db.adminCommand? Whenever I run the command db.adminCommand({ "currentOp": true, "op" : "query", "planSummary": "COLLSCAN" ...