What is the best way to pass multiple arguments to a JavaScript function inside a string?

UPDATE the function name wasn't the issue (accidentally copied wrong one). The problem was that I was sending a string! Thanks to mplungjan, the problem is now fixed!

This is the code snippet:

 $("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' id='ShowDet' data-role='button' data-transition='pop' onclick='function(" + order.OrderID +"," + order.Total + ")'>Details</a></td></tr>");

I have a JavaScript function:

function fun(id,t) {
    $("#HistHead").empty();
    $("#HistHead").append(t + id);
}

When I send only 1 argument, it works fine, but with more than 1 it fails. Also, the data-roll doesn't seem to have any effect. Any ideas?

Answer №1

It appears that you have named your function fun instead of function. Please ensure that you use the correct name in the onclick event.

Best regards

Answer №2

Ensure that the function name in your onclick event matches the actual function name being called in your HTML code.

Here is a sample code snippet that demonstrates the correct usage:

<!DOCTYPE html>
<html>
    <head>
    <script src="js/jquery.js"></script>
</head>
<body>
    <div id="HistHead">Test</div>
    <table id="GVHistory"></table>
    <script>
    $(document).ready(function(){
        order ={OrderID:12,Total:15};
        $("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' id='ShowDet' data-role='button' data-transition='pop' onclick='fun(" + order.OrderID +"," + order.Total + ")'>Details</a></td></tr>");

    });
    function fun(id,t) {
        $("#HistHead").empty();
        $("#HistHead").append(t + id);
    }
    </script>
</body>

Answer №3

To gain a clearer understanding, let me elaborate further.
Let's suppose: order.OrderID = "orderId1" and order.Total = "total100"

When you append this <tr> to the DOM, the value of order.OrderID and order.Total is included in your onclick function, not the variables themselves.

Your onclick function ends up as

onclick="fun(orderId1, total100)"
. Clicking this would result in an error, as orderId1 and total100 are undefined variables. The correct approach would have been to enclose these values in quotes to make them strings, with the necessity of escaping the quotes using \ to prevent interference with the string being appended.

In cases where multiple strings or variables need to be passed, it is advisable to use custom data attributes like data-xxx="xxx".

$("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' class='ShowDet ui-btn' data-transition='pop'  data-orderid='"+order.OrderID+"' data-ordertotal='"+order.Total+"'>Details</a></td></tr>");

$(".ShowDet").unbind("click").on("click", function (){
    var id = $(this).data("orderid");
    var t = $(this).data("ordertotal");

    $("#HistHead").empty().append(t + id);
});

Regarding the issue with data-role="button"
This particular jQuery Mobile attribute only functions when present in the DOM during initial page load. To incorporate dynamically appended elements, calling the corresponding widget becomes necessary. For buttons, utilizing css classes like .ui-btn can provide an easier solution for styling.

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

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script ...

The images are currently unavailable as they are being retrieved from the database

I am encountering an issue with displaying images. Initially, the images are posted and saved successfully in MongoDB. You can view it in the image belowhttps://i.sstatic.net/NatvV.png Then the images are fetched from the database and when displayed, the ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Encountering a StaticInjectorError in Angular 5.0

When I try to open the Dialog by clicking a button, I encounter the following error: ERROR Error: StaticInjectorError(AppModule)[UsertableComponent -> MatDialog]: StaticInjectorError(Platform: core)[UsertableComponent -> MatDialog]: ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

The process of AngularJS one-time binding is triggered twice

Why does the one-time binding get called twice? var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.bar = function() { console.log('bar'); return 'bar'; ...

Exploring Vue.js: Leveraging v-bind for multiple classes in Vue.js applications

Can someone assist me in figuring out how to apply multiple options to v-bind:class? In my Uno game, I need to determine the text color of cards based on their color property stored as a list of objects like this: ([{ Color: green, Value: 6}]. Here is my ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

Utilize a drop-down selector in JavaScript to search and refine the results

Looking for a way to enhance your product search form? Consider adding an option to select a specific shop from the dropdown menu. This will allow users to search for products within a particular store if desired. <form action="#" method="get"> &l ...

Selecting multiple values in a SelectMenu with Discord.js (DJS)

I want to be able to select multiple values, each corresponding to a specific role. For example: If I choose "member", the SelectMenu will assign the role "Member" If I choose "member" and "logs", the SelectMenu will assign the roles "Member" and "logs" ...

When the number of selected students exceeds zero, activate the collapsing feature in React

When the number of students exceeds zero, the collapse should automatically open and the text in Typography (viewStudentList) will display 'Close'. On the other hand, if the student count is zero, the collapse should be closed and the text on Typ ...

jquery toggle not working on second click

I need to constantly repeat two functions, but I am experiencing issues: function rotation () { plrotation(); function plrotation () { alert('pl'); $('#pl').toggle(300).delay(10000).toggle(40 ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

The compiler detected an unanticipated keyword or identifier at line 1434. The function implementation is either absent or not placed directly after the declaration at line 239

Having trouble implementing keyboard functionality into my snake game project using typescript. The code is throwing errors on lines 42 and 43, specifically: When hovering over the "window" keyword, the error reads: Parsing error: ';' expecte ...

The JScolor Color Picker has a slight misalignment

I am having an issue with the jscolor color picker on my webpage. The rainbow part of it appears offset within the rest of the picker. You can see what it looks like on my site here: (https://ibb.co/9N8dHXs). On my website, I have a large canvas for three ...

Pagination in Datatables

Here is the code snippet I am working with: $('#ldap-users, #audit-users').dataTable({ "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p& ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Ignore the first checkbox selection and increase the original value by .10 with each subsequent checkbox selection

In my scenario, there is a set of checkboxes that are linked to the pricing system. Specifically, I need the base price to remain unchanged when the first checkbox is ticked. Subsequently, for each additional checkbox selected, an increment of $0.10 shou ...

React App searching for unused static files

Currently, my React application is deployed on the Nginx web server. Accessing the application using the URL XX.XX.XX.XX works fine. However, I want to be able to access it through the URL XX.XX.XX.XX/myapp/frontend. To achieve this, I have set up a revers ...

Prioritizing reusability and scalability in the design of Vue.js application architecture

I am currently working on adapting an Application that was originally developed for a single country to be used in multiple countries (20+) with only slight modifications needed for each location. I am exploring ways to make the code reusable and scalable ...