javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach:

    for (buttonName in buttons){ 
         var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'</button>' 
}

I am struggling to correctly attach the function to an onclick event.

Any help or advice is greatly appreciated. Thank you!

Answer №1

It is not possible to include a Function instance within a string.

If the buttons variable is declared globally, it can be accessed by code within the onclick event handler attribute:

var htmlButton = '<button type="button" onclick="buttons[\''+buttonName+'\']()">'+ buttonName + '</button>';

However, the above method does not handle escaping characters properly, which could lead to security vulnerabilities if buttonName contains certain special characters like <, &, ', or ". To avoid this, these characters need to be escaped in both JavaScript and HTML where the strings are being embedded.

A more efficient approach is to refrain from creating HTML using concatenated strings. Instead, utilize DOM methods and native JavaScript objects to build your elements, thereby eliminating the complexities of dealing with nested strings.

var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode(buttonName));
button.onclick = buttons[buttonsName];

Answer №2

Consider updating your code to:

for (btnName in btns)
{
     var htmlBtn = 
         '<input' + 
         ' type="button"' +
         ' value="' + (btns[btnName]).replace(/"/gi, "&quot;") + '"' +
         ' onclick="' + (btns[btnName]).replace(/"/gi, "&quot;") + '()"/>';
}

Updated for clarity:

Since the <button> tag may not be consistent across browsers.

According to W3School:

Note: When using the button element within an HTML form, various browsers may submit different values. Internet Explorer will submit the text enclosed by the <button> tags, while other browsers will submit the content of the value attribute. It is recommended to use the <input> element for creating buttons within an HTML form.

Answer №3

Perhaps what you're searching for is something along these lines:

for(btnName in btnsCollection) {
    var htmlBtn = '<button type="button" onclick="window.btnsCollection[\''+btnName+'\']()">'+btnName+'</button>';

Instead of displaying the entire function within the onclick attribute, this approach only shows the callable function name. Just ensure that btnsCollection is within the appropriate scope.

Answer №4

Although jquery is not a requirement in this particular scenario, I am developing code for a jquery plugin. This is the most effective solution I have come up with so far:

$.each(buttons, function(name, fn) {   

   $('<input type="button" value="'+name+'" />').click(function() { fn.apply() }); 


  });

I have yet to discover any potential drawbacks in using the call or apply property, but for now, it functions perfectly.

I would greatly appreciate your thoughts and comments on this.

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 methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

Assign the array value to all inputs that share the same class tag

Does anyone know how to iterate through all tags with the same className and retrieve their values? var quantities = []; $(".add_more_items").each(function(){ quantities.push($(this).val()); }); Here is an example of the result: ['1&apo ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I wou ...

Anticipated a response in the form of an object, however, a string was delivered instead

After recently updating to v14 of discordjs, I've been encountering numerous errors, including the one below. It seems a lot has changed since my last coding session, and I'm a bit unsure about what modifications are needed to ensure this ping sl ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

``The Vue.js routing system is determined by the incoming data received

Working with VueRouter to navigate to a component based on payload. { path: '/foobar', name: 'foobar', component: foobar, } { path: '/foobar', name: 'foobarSuccess', component: foobarSuccess, query: { ...

Struggling with a TypeError in React/Next-js: Why is it saying "Cannot read properties of undefined" for 'id' when the object is clearly filled with data?

Encountering an issue with a checkbox list snippet in Next-js and React after moving it to the sandbox. Each time I click on a checkbox, I receive the error message: TypeError: Cannot read properties of undefined (reading 'id') This error is co ...

React component not displaying HERE map controls

Having trouble implementing zoom in and zoom out controls on HERE maps in React. Despite following the documented steps, I am unable to find a solution. I have meticulously followed all instructions provided at: The link to my map component can be found ...

Looking for suggestions on how to bring this idea to life

I'm searching for a solution using JavaScript, jQuery, or Angular. I've created three random arrays like this: for example: (The values are randomly generated from the array ['member', 'medical', 'rx', 'disabi ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...

Generating a .png image using the data received from the client [node]

I need to create a highchart client-side and save a PNG of that chart server-side. After successfully generating the highchart and converting it to a PNG using the following function: function saveThumbnail(graph_name, chart) { canvg(document.getEleme ...

Tips for setting background colors as a prop for Material UI cards in React JS

Currently utilizing the Material UI next framework to construct a wrapper for the card component. This customized wrapper allows for personalization of the component. I have successfully extended the component so that the title and image within the card ca ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...

Pattern matching: Identify text elements specifically within an HTML tag

I've been experimenting with a text highlighting script. Check out my initial attempt here. Here's the code snippet: http://jsfiddle.net/TPg9p/3/ However, I encountered a problem – it only works with simple strings and not those containing HT ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...