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

Is there a method to retrieve the subdirectories and files currently present on a given URL?

Picture having a file on your system with the following URL: I am curious if there is any software, command, or script that can retrieve subfolders/files based on a given URL. For instance: Input parameter: http://my.page/folder_1/ Output: http://my.p ...

Navigating through multiple layers of React refs can be achieved using a technique called travers

Hey there, I'm currently working on extracting all the a tags from within the #header-nav section. const HeaderNav = (props) => { // setState const $target = useRef(null); const $component = $target.current.querySelectorAll('a'); return ...

Tips for setting a jQuery variable equal to the value of a JSON object

When I try to assign courseid and batchid as defaults using defaultValue => defaultValue: courseid and defaultValue: batchid, the values are not being saved correctly in my database. $(document).ready(function() { var courseid = null; var bat ...

Submit information from an HTML form to a PHP script and then send the response back to the client using AJAX,

Looking to run a PHP script using AJAX or JavaScript from an HTML form and then receive the results on the HTML page. This is what my changepsw.php file looks like: <?php // PHP script for changing a password via the API. $system = $_POST['syst ...

What is the best method for comparing two JSON objects in AngularJS?

I am working with two JSON objects. $scope.car1={"Sedan":{"Audi":["A4","A3"]},"Hatchback":{"Maruthi":["Swift"]}}; $scope.car2={"Hatchback":{"Maruthi":["Swift"]},"Sedan":{"Audi":["A3","A4"]}}; I have attempted to compare these two objects using the co ...

Having trouble with the chaining of AJAX calls using Promises?

I am currently attempting to send a POST request (technically a DELETE) to a php page called delete_post.ajax.php. This request takes data from my AJAX call and utilizes it to delete an item from the database. After deletion, I want my AJAX to then send a ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...

How can you ensure seamless synchronization while logging in a user with ReactJS and retrieving data from the API?

Is there a way to synchronize and run these two functions in succession before calling console.log(user) and setLogin()? The goal is to ensure that all the information retrieved from the API is available in the user context before activating the setLogin() ...

Upon employing the setTimeout method, the element with the id "sign-in-block" will have its display style set to "none" after a delay of 1000 milliseconds

I incorporated the setTimeout() function to make the HTML component appear for 1 second upon pageload. However, I would prefer this component not to load at all. Should I set the delay in the setTimeout() function to 0ms? Alternatively, is there another ...

The Bootstrap modal is not properly clearing all attribute properties when it is hidden

Alrighty, so I've got this modal set up: <div id="modal-container" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content center-block" style="displ ...

"Upload a text file and create a JavaScript variable that contains the text within it

I am currently developing a library and I need to add a feature that reads the contents of a text file. Currently, it only returns the path. How can I modify it to return the actual content of the file? function displayFileContent() { var file = do ...

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Incorporating data retrieved through AJAX requests into a Python function

The Flask application described below continuously makes Ajax calls to a backend index function that queries a database and injects the results into a template. However, the injected data is not being refreshed after the Ajax calls are completed, leading ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

Exploring the Latest PHP Popup Upgrade

Hey everyone, I'm currently facing an issue with updating my MySQL database. I have a popup window that is supposed to update it without any errors, but for some reason, it's not actually updating the database. Can anyone help me figure out what ...

Passing a parameter to an AngularJS directive, which triggers the opening of an ngDialog, and subsequently updating the value to reflect changes in the root scope

Struggling with a persistent issue here; Essentially, I have a directive that triggers an ngDialog to open. This directive should be able to receive a variable from the root scope. The directive contains a click event that opens an ngDialog which then use ...

Sending files to the server through HTML5

Could someone assist me with uploading a file after it has been selected using HTML5? Here's the code snippet for selecting the file: <input type="file" .... /> The input field above allows you to choose a file, but I also need help with uploa ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

PHP data is not displayed by Ajax

I seem to be encountering a bit of trouble. I am attempting to utilize ajax to retrieve data from a PHP server, which in turn fetches it from a MySQL database, and then display it within a specific HTML tag location. However, for some unknown reason, nothi ...