An uncaught SyntaxError occurred due to an omission of a closing parenthesis after the argument list in code that is otherwise

I have a Javascript code that sends an Ajax request and upon receiving the data, it creates an "a" tag with an onclick event that triggers another method along with a parameter. Below is the implementation:

function loadHistory() {
        var detailsForGet = {
        userId: sessionStorage.getItem("userName")
    }
    $.ajax({
        type: "GET",
        url: "https://localhost:44326/User/getTwitterSearchHistory",
        data: detailsForGet,
        success: function (data) {
            jQuery.each(data, function (index, item) {
                console.log(item)
                $('<a href="#" onclick="historySearch(' + item + ')">' + item + '</a><br/>').appendTo('#forHistory');
            });
        }
    });
}

function historySearch(text) {
    console.log(text)
    document.getElementById('tweetSearching').innerHTML = "Searching...";
    $.getJSON("https://localhost:44326/api/Twitter/GetSearchResults?searchString=" + text)
        .done(function (data) {
            if (data.length == 0) {
                document.getElementById('tweetSearching').innerHTML = "No matches Found!";
            }
            else {
                document.getElementById('tweetSearching').innerHTML = "Found " + data.length + " matches!";
                console.log(data)
                document.getElementById('searchResults').innerHTML = "";
                $('<h3 style="text-align:center; color: white">Search Results</h3> <hr/>').appendTo('#searchResults');
                $.each(data, function (key, item) {
                    $('<ul style="list-style:none;"><li><span style="font-weight: bold; color: white">Post </span><span style="color: white">' + item.FullText + '</span><br/><span style="font-weight: bold; color: white">Uploader</span><span style="color: white"> ' + item.CreatedBy.Name + " @" + item.CreatedBy.ScreenName + '</span><br/><span style="font-weight: bold; color: white">Date</span><span style="color: white"> ' + formatDateTwitter(item.CreatedAt) + '</span><li/><hr/></ul>').appendTo('#searchResults');
                });

            }
        });
}

When I attempt to click on the "a" tag, I encounter an error

Uncaught SyntaxError: missing ) after argument list

This issue only arises when calling a method with a parameter in the onclick function. Previously, I tried calling a function without a parameter, and it worked fine. However, passing a parameter results in this error.

Am I missing something important here?

Answer №1

If the value of your variable is a string, it's important to remember to wrap it in quotes when using onclick JavaScript. When working within an HTML string that already uses single quotes, you can include single quotes by encoding them as \x27.

$('<a href="#" onclick="historySearch(\x27' + item + '\x27)">' + item + '</a><br/>').appendTo('#forHistory');

For more information, check out: How to Escape Quotes in JavaScript

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

ElementUI Cascader not rendering properly

Utilizing elementUI's cascading selector to present data, I have crafted this code in accordance with the official documentation. <el-cascader v-model="address" :options="addressOptions" :props="{expandTrigger: 'hover'}" ...

Discover the concealed_elem annotations through the power of JavaScript

As I work on my new website, I am struggling with narrowing down the web code. I came across a solution that seems fitting for what I need, but unfortunately, I can't seem to make it work: I attempted the non-jQuery solution, however, I must be missi ...

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

There appears to be some lingering content in the JQuery Mobile slide-out dialog box

My jQuery mobile slide out dialog box is experiencing an issue. The first time the slide out occurs, a comment box appears where users can enter comments and then submit them, followed by a "THANK YOU" message. However, when the user closes the dialog box ...

Customizing demonstration code for EventDrops with D3.js (by marmelab) - what are the best strategies?

After discovering the non-Node.js version of the EventDrops library for D3 on GitHub, I successfully implemented the example on my own server. You can find more details and the example code in this blog post here. However, I'm currently facing two is ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

Simplify nested JSON data

I'm struggling with a JSON object that looks like this: const people = { name: 'My Name', cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: ...

Error callback not being invoked on save() method in AngularJS service

So I am currently using the AngularJS Restful Service $resource in my project. However, when I try to call the $save function and provide an error callback, it does not get invoked. Surprisingly, even though the server sends a 418 error, which is not a suc ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...

Combining Ajax Form with Django to handle and display errors in form submissions

I am attempting to save information from a form into my Database using Django and Python for the backend. Below is the HTML form: <form> <center> <div class="container-fluid"> <div class="row"> <div clas ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Performing an HTTP GET Request in Node.js or Express.js

Currently, I am working with express.js and require assistance in making an HTTP GET request to retrieve JSON data. Can anyone recommend some reliable node js/express js modules or libraries that can help me with performing get/post requests? ...

Navigate through the list of options by scrolling and selecting each one until the desired element is

Hey, I've got this AngularJs directive that selects an item based on the "key-pressed" event, and it's working perfectly. The issue arises when there is a scroll bar since the elements get hidden, making it difficult for me to see them. You can ...

Unlimited Caching: A Guide to Storing HTTP Responses permanently

Is there a way to send an HTTP response that will be cached by any client indefinitely, so that the browser can retrieve it from the local file system without making any new HTTP requests when needed? Just imagine using this for versioned client code in a ...

Enhancing elements with fade-in effects upon hovering

Is there a way to incorporate a subtle fade in/fade out effect when hovering over items on this webpage: http://jsfiddle.net/7vKFN/ I'm curious about the best approach to achieve this using jQuery. var $container = $("#color-container"), ...

php Stristr() function behaving unexpectedly

I recently came across this code on a coding website and made some modifications to it. However, I'm facing an issue with the stristr() function not behaving as expected. For instance, when I input "E", the output displays "Eva" five times, and when I ...

Determine if a point within a shape on a map is contained within another shape using Leaf

I have extracted two sets of polygon coordinates from a leaflet geoJSON map. These are the parent and child coordinates: var parentCoordinates=[ [ 32.05898221582174, -28.31004731142091 ], [ 32.05898221582174, -2 ...

Pressing the button results in no action

I am currently developing a program that randomly selects 5 words from a database and inserts them into an array. Although the page loads correctly initially, nothing happens when the button is clicked. None of the alerts are triggered, suggesting that the ...

Is there a way to update a child component in React when the parent state changes, without utilizing the componentWill

I am currently working on developing a JSON editor using React, but I am facing an issue with the library I am utilizing not having a componentWillReceiveProps hook. As someone relatively new to React, I am trying to find a way to automatically update th ...