dynamically passing arguments to an onclick function

I am experiencing an issue with the following HTML element that has an onclick() function dynamically attached. When trying to call the function, it throws an error stating that "ST" is not defined. The variable passed as name is something like "ST-123". Can someone assist with resolving this error?

hubName = "ST-123" ;

IdCell.append("<button type='button' class='btn-link' style='float:right; margin-right:-6px; margin-top:-11px;' onclick='unPair($(this),"+name+")'>
 <img src='../images/link-minus.png'> </button>");

In this scenario, the idCell represents one of the table cells.

Answer №1

The issue lies in the fact that your second argument is not a string.

onclick='unPair($(this),"+name+")' 

will result in

onclick='unPair($(this),ST-123)'

Because ST-123 is not recognized as a string, it will attempt to subtract 123 from ST. If ST is not defined, an exception will be thrown.

Due to the difficulty of using single quotes within the onclick attribute, you can opt for double quotes. However, since your string already begins with a double quote, you must escape it by adding a backslash like so:

onclick='unPair($(this),\""+name+"\")'

This will then be translated to:

onclick='unPair($(this),"ST-123")'

Answer №2

Utilize jQuery more efficiently

const newButton = $('<button />', {
    type    : 'button',
    'class' : 'btn-link',
    css     : {
        float       : 'right',
        marginRight : '-6px',
        marginTop   : '-11px'
    },
    on      : {
        click : function() {
            unPair( $(this), name );
        }
    }
}),
    newImage = $('<img />', {
        src : '../images/link-minus.png'
});


IdCell.append( newButton.append(newImage) );

Answer №3

Make sure to pass the value as a string

 onclick=\"unPair($(this),'"+name+"')\"

Alternatively, you can utilize double quotes

 onclick='unPair($(this),\""+name+"\")'

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

What is the most effective method for retrieving a PHP return value using Ajax?

As I work on creating a validation form in Ajax and PHP, I find myself unsure of how to fetch values from PHP. Can anyone guide me through this process? For instance: The validation form exists in index.php while the page containing the function is check ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

Capturing the unknown elements in a deeply nested array

I'm trying to create a helper function that will return 0 if an element in a nested array is undefined. The issue I'm facing is that when the first index fails and returns undefined, the function should catch errors at subsequent indexes but it&a ...

Excluding a Spec File in Your Protractor Configurations

I have a scenario where I have 10 spec files all named *********.test.js. I need to run tests on all 9 of these files, excluding the file named Idontwantyou.test.js. Currently, I am locating my spec files in the config.file using: specs: ['*.test.js ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Waiting for the execution of JavaScript in Selenium-Webdriver is essential for ensuring the

Currently, I am utilizing selenium-webdriver in nodeJS instead of Java. My issue lies with using this.getPageSource(), as it returns HTML without waiting for the execution of JavaScript. Consequently, some elements that are loaded by JS do not appear in t ...

The jquery live click event is not functioning properly on iPad devices

I am experiencing an issue with a webpage that has the following code to bind click events <script type="text/javascript"> $(".groupLbl").live("click", function(e) { var $target = $(e.currentTarget); ..... $.getJSON("/somelink.js ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

What is the solution to incorporating a scrollbar in a popup when I increase the zoom level?

When trying to add a scrollbar to the popup, I am facing an issue where the scrollbar does not appear when zoomed in to 75% or 100%. It works fine for fit screen but not on zoom. Can anyone help me identify what is wrong with my code and suggest how to han ...

In the case where all children are classified as "concealed," utilize jQuery to display a <p> tag with the message "No results were found."

I'm in the process of developing a glossary page that includes filtering based on a search term. The entire functionality is being implemented using jQuery through a straightforward script. $("#txtSearch").on('keyup', function() { var s ...

Complete Guide to Node.JS CRUD Delete Functionality

Currently, I am developing a node.js CRUD application that interacts with MongoDB. The main features of this app are allowing users to upload photos, edit details related to the photos, and delete them from the database. However, I am facing challenges i ...

Use Angular Js to add HTML inner elements to the table

This is my custom HTML code: <body> <div ng-app="tham" ng-controller="tham-control"> <div class="container"> <table class="table table-bordered table-striped"> <thead> ...

Submit button on Ajax form causes automatic page refresh

After adding a simple Ajax form to my WordPress website, I encountered an issue where the validation works fine, but instead of sending the email, the form refreshes after submitting. Here is the code snippet: <script type="text/javascript"> jQ ...

The value could not be retrieved because the input name depends on the array index

To determine the name of the input based on the array index, use the following method: <div id="editAboutSantences<%=i%>" class="edit-container"> <div class="input-container"> <label> content: </label> ...

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

Creating a unique Bootstrap Navbar design with vertically staggered elements

https://codepen.io/bencasalino/pen/NWPLLYQ <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto nav-flex-icons"> <li class="nav-item"> <a class="nav-link p-0 color-white" h ...

The 'split' property is not present on the 'string | number | {}' type

Just starting out with Typescript and I've encountered an error stating that the split method does not exist on type number. I've tried narrowing down the type by checking the value's type, but so far it hasn't been successful. Below is ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Inserting documents into an array of objects in MongoDB

I am facing challenges while attempting to insert multiple objects into an array of objects in my development. The issue arises when trying to add more than one object with the same structure but different content. This is the structure of the groups coll ...