Summernote - Add Text while maintaining formatting requirements

Currently, I am facing an issue where inserting a string of text from a dropdown list into the Summernote text editor results in the closing of formatting tags such as <'strong'>, <'p'>, and more.

After inserting the string "AND", the HTML looks like this:

Bob AND Loves Ice Cream and Cake.  How about You?

<p><span style="font-size: 12px;"><b>Bob </b></span>AND <span style="font-size: 12px;">
<b>I&nbsp;</b></span><span style="font-size: 12px;">
<b>Loves Ice Cream and Cake. &nbsp;How about You?</b></span>

The challenge is to prevent the automatic closing and opening of tags around the cursor position. I have explored using insertNode() and insertText() functions but faced the same issue with both.

Do you have any suggestions or ideas on how to tackle this problem? Thank you!

EDIT: Below is a snippet of code showcasing the insertion at the cursor. I am enhancing Summernote's button functionality with the UppercaseButton feature.

 var UppercaseButton = function (context) {
    var ui = $.summernote.ui;

    // create button
    var button = ui.button({
        contents: '<i class="fa fa-child"/> Uppercase',
        tooltip: 'Highlight a data attribute that you would like to make uppercase',
        click: function () {

            var range = $('#taBody').summernote('createRange');
            var newText = range.toString();
            console.log("newText: " + newText);
            console.log(range);
            context.invoke("editor.insertText", newText.toUpperCase());
        }
    });

    return button.render();   // return button as jquery object
}

Answer №1

In my strategy, I aim to identify the current node context where the cursor is located and insert the desired text into that node.

function insertTextAtCursor(inputText) {
        // deleteContents() will replace any highlighted text, if there is any
        let newRange = $("#taBody").summernote("getLastRange").deleteContents();

        // Insert the desired text within the formatted tag of the first part of the highlighted text. This way, the formatting will be applied to the inserted text
        newRange.sc.textContent = newRange.sc.textContent.substring(0, newRange.so) + inputText + newRange.sc.textContent.substring(newRange.so, newRange.sc.textContent.length);

        // Update the cursor position to just after the inserted text
        $("#taBody").summernote('setLastRange', $.summernote.range.create(/* start container */newRange.sc, /* start offset */ newRange.so + inputText.length).select());
    }

var UppercaseButton = function (context) {
    var ui = $.summernote.ui;

    // create button
    var button = ui.button({
        contents: '<i class="fa fa-child"/> Uppercase',
        tooltip: 'Select a data attribute to convert to uppercase',
        click: function () {
            insertTextAtCursor(newText.toUpperCase())
        }
    });

    return button.render();   // return button as jquery object
}

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 way to designate whether the <ul> element is displayed horizontally or vertically?

For example: <ul> <li>a</li> <li>b</li> </ul> The default output is: ab But I am looking for: a b Is there a way to achieve this? ...

How can you conceal an object based on specific conditions in JavaScript?

In my JavaScript code, I am working with an object that stores multiple values. However, I want to be able to hide a specific object under certain conditions. Here is the data structure: $scope.sort={ National : { prop: "Country", classes: { md: ...

React.js onClick does not display the dropdown

Hello, I have a question regarding my navbar icon functionality. When I click on the icon, it is supposed to open a dropdown menu. However, although the div name changes when clicked, the CSS properties remain the same as the initial class. I am unsure w ...

Overflow-x in HTML5 Websites

I recently launched my website in the "alpha" stage - I have implemented full mobile support using media queries. It displays perfectly when the browser window is resized, but I noticed a strange space to the right of everything on my Samsung Galaxy Note ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Converting an HTML table to a CSV file with pure JavaScript

I need to implement a CSV download feature on my website that converts the HTML table into downloadable content. While searching for a suitable plugin, I came across resources like http://www.dev-skills.com/export-html-table-to-csv-file/ which uses PHP s ...

Guide on incorporating a library into your Ionic application without the need to upload it to npm

Recently, I successfully created an Angular application, an Ionic application, and a custom library in my workspace. I am able to import the library files into my Angular application but facing challenges when trying to import them into my Ionic applicat ...

jQuery's simple scrolling feature is currently not functioning as intended

Could someone explain why the following code snippet is not functioning correctly? The objective is to smoothly scroll the screen to an anchor destination, taking into account the height of a fixed header with ID "jeden". $(document).ready(function() { ...

Tips for transferring an MVC model to a UI-bootstrap modal

Trying to implement an Angular/bootstrap modal for editing MVC ApplicationUser scaffolded views. Came across jquery examples but want to stick with angular-ui or plain bootstrap for consistency in modals. Unclear on how the MVC controller is being called f ...

Gather information from users using Node.js and integrate it with Stripe

As I am new to Node.js, my goal is to utilize nodejs & Stripe to gather user data such as name, phone number, email, city, etc. This way, I can easily identify the user from the Stripe dashboard along with all their corresponding information. on the server ...

Learn how to display HTML content in trNgGrid using the $sce.trustAsHtml method

I am currently working with a table that has search options implemented using trNgGrid.js. The data for this table comes from a Sharepoint list where one of the columns contains HTML content that I need to display. To achieve this, I attempted using $sce. ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

In ASP.NET MVC, use CSS styling specifically for Partial Views by encapsulating the styles within a `<style scoped>` tag

A new HTML attribute has emerged, known as scoped, however, it is currently only supported by Firefox. This attribute allows you to declare internal styles solely for the parent element. I am curious if it is feasible to replicate this functionality in AS ...

Can you explain the function of the "staticMoving" property in TrackballControls?

I was exploring the library module known as THREE.TrackballControls when I came across an interesting property within an instance of the module called staticMoving. This property appears to be connected to another property called dynamicDampingFactor. Howe ...

The ability to rate the product in Livewire:Laravel is exclusively reserved for buyers

I have integrated the Livewire rating system into my Laravel e-commerce platform. Currently, all users can rate and comment on any product. However, I want to restrict this privilege to only buyers. ProductRatings.php class ProductRatings extends Componen ...

Accessing a PHP variable within an AJAX handling script

Upon user login, the email is stored in $email (I also tried global $email). Subsequently, a form allows the user to input their roommate's name to search for existing appointments. Incorporating AJAX $("#reserveAPickupAppointmentForm3").submit (fun ...

utilize Angular's interface-calling capabilities

In the backend, I have an interface structured like this: export interface DailyGoal extends Base { date: Date; percentage: number; } Now, I am attempting to reference that in my component.ts file import { DailyGoal } from '../../interfaces' ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

What are the potential causes of an asynchronous error in a WebGLRenderingContext?

While running an animation loop, I encountered a peculiar error message that reads... GL ERROR :GL_INVALID_OPERATION : glDrawElements: Source and destination textures of the draw are the same. This error seems to occur randomly after 2 or 3 animation fr ...

Several jquery libraries are experiencing malfunctions

<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".slidingDiv").hide(); $(".show_hide").show().click ...