The process of dynamically adding buttons in Summernote with the inclusion of a parameter

Currently, I am working on developing dynamic custom buttons for my summernote wysiwygs. However, I have encountered an issue. My goal is to pass the data that I am iterating through to the button's render function. Unfortunately, since the context is already being passed as a parameter, I am a bit stuck in figuring out the best approach.

Below is the relevant code snippet:

var formButtons = {};
var formButtonIds = [];
if(FormsModule.currentForm) {
    for(var i=0; i<FormsModule.currentForm.fields.length; i++) {
        var field = FormsModule.currentForm.fields[i];
        var fieldId = 'button_' + i;
        formButtons[fieldId] = (function (context) {
            console.log(context);
            console.log(field);
            var ui = $.summernote.ui;
            var tooltip = 'Insert ' + field.title;
            // create button
            var button = ui.button({
                contents: HelperModule.getTitle(field.title),
                tooltip: tooltip,
                click: function () {
                    context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
                },
            });

            return button.render();
        });
        formButtonIds.push(fieldId);
    }
} 
$("#form-modal #form-form .wysiwyg").each(function(index, wysiwyg) {
    var content = $(wysiwyg).summernote('code');
    $(wysiwyg).summernote('destroy');
    $(wysiwyg).summernote({
        buttons: formButtons,
        toolbar: [
            ["style", ["style"]],
            ['font', ['bold', 'underline', 'clear']],
            //['fontname', ['fontname']],
            ["color", ["color"]],
            ["para", ["ul", "ol", "paragraph"]],
            ["mybutton", formButtonIds],
            ["table", ["table"]],
            ["insert", ["link"]],
            ["view", ["codeview"]],
        ],
    });
    $(wysiwyg).summernote('code', content);
})

In an attempt to pass the field value to the formButtons[x] function without replacing the context's value, I tried the following:

    formButtons[fieldId] = (function (context) {
        console.log(context);
        console.log(field);
        var ui = $.summernote.ui;
        var tooltip = 'Insert ' + field.title;
        // create button
        var button = ui.button({
            contents: HelperModule.getTitle(field.title),
            tooltip: tooltip,
            click: function () {
                context.invoke("editor.insertText", '<span clas="field-input-button">#' + field.title + '#</span>');
            },
        });

        return button.render();
    })(field); 

After exploring this option, the console output for both field and context displayed the correct field value.

Answer №1

Seems like the field.title is being rendered at click time, causing it to be out of scope.

Here's a suggestion:

formButtons[fieldId] = (function(context) {
  console.log(context);
  console.log(field);
  var ui = $.summernote.ui;
  var tooltip = 'Insert ' + field.title;
  // create button
  var button = ui.button({
    contents: HelperModule.getTitle(field.title),
    tooltip: tooltip,
    data: { fieldtitle: field.title },
    click: function() {
      context.invoke("editor.insertText", `<span clas="field-input-button">#${this.dataset.fieldtitle}#</span>`);
    },
  });

  return button.render();
})(field);

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

When implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

Master the Art of Animating Letters in the DOM by Navigating Through Any Array of Characters

I am attempting to implement a typewriter effect animation where a new message is displayed and animated as I type into an input box. Initially, I tried using a global char variable to iterate through each element of the array. However, whenever I passed ...

Accordion nested within another accordion

I am facing a challenge while trying to nest an accordion within another accordion. The issue is that the nested accordion only expands as much as the first accordion, requiring additional space to display its content properly. Any assistance with resolvin ...

Ways to repair the mouse hover transform scale effect (animation included)

I am currently facing an issue with my GridView that contains images. When I hover over the top of the image, it displays correctly, but when I move to the bottom, it does not show up. After some investigation, I suspect that there may be an overlay being ...

Struggling with the Nivo slider not loading properly?

Check out my personal website. I'm having an issue with my Nivo slider not displaying properly - it just keeps loading. Any ideas on why this is happening and how I can fix it? Below is the CSS I am using: #slider { position:relative; width: ...

AngularJS Banner: Displaying Current Calendar Week and Increasing by 10 Days

I'm brand new to Angular and currently encountering some issues. Here's what I'm trying to create: I need to display the current Date: yyyy-MM-ss (Functional) I want to show the current Calendar Week: yyyy-Www (Not Working) When a butto ...

VueX Error: The store property is undefined and cannot be read

In my vue.js store, I am able to access the state parameters within the computed section of a component: computed: { BASE_URL () { return this.$store.state.BASE_URL; } However, when attempting to access the store in the methods of the same co ...

Is there a way to solely adjust the color of a -box-shadow using jquery?

Looking for a way to incorporate tinycolor, a color manipulation framework, into setting a box-shadow color. Instead of directly setting the box-shadow with jQuery, you can use tinycolor on an existing color variable. $("CLASS").css("box-shadow", "VALUE") ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

The CORS policy has blocked the request due to the header being set

Recently, I've been working on building a server using NodeJS with express and have come across an obstacle regarding the CORS policy. In my server's code snippet, this is what I have: app.get(`/important`, function(req,res){ fs.readFile(&apo ...

My regular expression isn't functioning properly. Can someone please assist me in troubleshooting and resolving this issue?

Here is my code snippet: property_unit_plan.post('/bulkAdd',(req, res) =>{ Array.prototype.forEach.call(req.body, element => { db.sequelize.query('CALL sp_property_unit_plan_add_bulk( :unit_size_range, :no_of_bedrooms, :no_ ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

Can a variable in Angular be dynamically assigned a value depending on the screen size with the help of Bootstrap?

Within my Angular component, I have defined a global variable as follows: visibleDays = 7 I am looking for a way to dynamically adjust this value based on the screen size. Specifically, for smaller devices like "sm" or "xs", I would like the value to be s ...

The inability to access a route with an authentication guard in the app controller is causing the validate function in the local strategy file to not run

While trying to access my login route in the app.controller.ts of my rest api built with Nestjs and Prisma, I encountered a 401 error response. I have been closely following the official documentation provided by Nestjs on authentication (https://docs.nest ...

The date of posting will always be '0000-00-00 00:00:00'

I'm experiencing an issue with my JavaScript code for writing reviews. Previously, it worked fine, but now the 'datePosted' column consistently outputs the default '0000-00-00 00:00:00'. writeReview(request, respond) { va ...

What is the best way to execute my lambda function for a designated period and then shut down smoothly?

Since AWS Lambda has a maximum timeout of 15 minutes, I am looking to execute my lambda for 14.5 minutes and then gracefully exit before the time limit is reached. The lambda is using the AWS SQS SDK to poll for messages with ReceiveMessages. Is there a w ...

Function wrapper intended for axios

How can I create a wrapper function for axios? I am looking to create a function that can return axios, allowing for easy substitution with another fetch API in the future. This is what I have attempted so far: import axios from 'axios' expor ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

jQuery validation: Form failing to pass validation

I have encountered an issue with a simple JavaScript file on my ASP.NET MVC website. While the input masking feature works smoothly, the form validation seems to be malfunctioning. Even when I enter a phone number that is only 4 digits long, the validation ...

Stop a user from adding duplicate tasks

I have developed a JavaScript code for creating a todo list. Currently, I am working on the phase of adding tasks to the list. The user wants to ensure that if a task is entered once, it cannot be entered again. const taskInput = document.getElementById(&a ...