Tips for implementing a textform as an alternative to an editable div using this specific code

UPDATE: I managed to successfully implement the code below with some assistance from the comments. However, it seems to apply the changes to all text rather than just the highlighted text.

$(".boldtrigger").click(function() {$(".text").toggleClass("bold");});
$(".italictrigger").click(function() {$(".text").toggleClass("italic");});
$(".underlinetrigger").click(function() {$(".text").toggleClass("underline");});
.bold { font-weight: bold;}
.italic {font-style: italic;}
.underline {text-decoration: underline;}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
</head>

<body>
<a href="#" class="boldtrigger">Bold</a> <a href="#" class="italictrigger">italic</a> <a href="#" class="underlinetrigger">underline</a>
<textarea class="text">Here is the text.</textarea>
</body>
</html>

Is there a way to convert this div into a textarea box instead? Although it functions correctly at present, it does not meet my requirements when submitting a form. How can this be achieved?

$(document).ready(function() {$('#jBold').click(function() {document.execCommand('bold');}).find('#fake_textarea').removeAttr('disabled').trigger('focus');});
$(document).ready(function() {$('#jUnderline').click(function() {document.execCommand('underline');}).find('#fake_textarea').removeAttr('disabled').trigger('focus');});
$(document).ready(function() {$('#jNewline').click(function() {document.execCommand('insertHtml', false, '<br>');}).find('#fake_textarea').removeAttr('disabled').trigger('focus');})
        #fake_textarea {
  width: 100%;
  border: 1px solid red;
  height: auto;
  min-height: 200px;
}

button {
  font-weigth: bold;
}
span {display: table;}
<!DOCTYPE html>
<html>
<head>
    <script src="http://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
    </head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="jBold" type="button"><b>B</b></button> <button id="jUnderline" type="button"><u>U</u></button> <button id="jNewline" type="button">New Line</button>
<div id='fake_textarea' contenteditable='true'></div>
</body>
</html>

Answer №1

Appreciate the assistance, but I stumbled upon an older post on this vintage BBcode site that provided a solution to my issue. The code remains intact when submitted through a form and displays the HTML results. There's also an option to include a NextLine button by tweaking the code, which proved quite helpful. By the way, for this one, remember to place the JavaScript in the header section.

function formatText(el,tag){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);
var newText='<'+tag+'>'+selectedText+'</'+tag+'>';
if(document.selection){//IE
document.selection.createRange().text=newText;
}
else{//Moz
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
}
}
<form name="myForm">
<textarea name="myTextarea" rows = "12" cols = "50">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea><br>
<input type="button" value="Bold" onclick="formatText (myTextarea,'b');" />
<input type="button" value="Italic" onclick="formatText (myTextarea,'i');" />
<input type="button" value="Underline" onclick="formatText (myTextarea,'u');" />
</form>

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

Error message in reactjs: When reloading, the function is not recognized as .map

When using material ui components within a .map of an array, attempting to modify one of the displayed values causes my app to crash and displays an error saying that .map is not a function. Below, I will share the code where this issue occurs. <div cl ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

What is the process for setting a linear gradient border color on a table row's border?

Currently, I am attempting to apply a linear gradient border color to the table row. Below are the codes for the table: td:first-child { border-left: 1px solid black; border-bottom-left-radius: 50px; border-top-left-radius: 50px; } td:last-child { bor ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Filtering nested objects in ReactJS can be achieved by utilizing methods like map

Data sample: nodes:[ { label:"Egor1", value:"Egor1", restorePoint:"25/10/2017 10:00:29 PM", vmcount:"2", restorePointsCount:"", children:[ {label:"disk111111111111111", value:"disk1", restorePoint:"3 day ...

What is the best way to link a Nav.Link to an ".html" webpage?

My website has a react navbar, but I am encountering issues when trying to redirect the page to an .html file. Here is the code snippet of the component I am using, with the href reference pointing to the QR CODE page at the same level as the component pa ...

Creating three cards with identical height using Bootstrap and flexbox techniques

I am struggling to align 3 blocks in height and keep the yellow block fixed at the bottom of its parent container. After trying different solutions, this is the outcome I have: https://i.sstatic.net/QOHsV.png The yellow block is not positioned correctly ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

Unable to establish a local dependency link with npm

Attempting to connect my local project testabc123 to myproject using the usual method: cd testabc123 npm link cd ../myproject npm link testabc123 However, encountering an error message: npm ERR! code E404 npm ERR! 404 Not Found - GET http://registry.npmjs ...

Is there a way to prevent the back button from functioning in my web browser?

How can I prevent the back button from being used on my webpage? Can you provide a list of possible methods to achieve this? if($data->num_rows > 0){ while($row = $data->fetch_assoc()){ header('Location:../cashier.php&apo ...

Can we stub these types of functions in any manner?

One file named helperFunction.js contains the following code: module.exports = (arg1, arg2) => { \\function body } To use this function in another file named file.js, you can simply call it like this: let helperFunction = require(' ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...

The class container-fluid from Bootstrap does not seem to be functioning properly within a Django environment

<div class="container-fluid"> <div class="row"> <img class="graph" src="{% static 'images/graph.png' %}"/> </div> </div> Hey there! I'm trying to make the graph.png static image fill the entire width of ...

Some pages are compatible with JS while others are not... Although, the file can be found in the page source

I have limited knowledge in javascript, so I often find myself copy-pasting code. Currently, I am working on a website that includes a navigation sidebar. I have implemented a script to toggle a class that sets the display property to none. $(document).rea ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

Exploring case scenarios within a function reliant on the instanceof operator (JEST)

Encountering a problem while writing unit tests for a function with instance checks. The business logic is as follows: let status = new B(); const testFunction = () => { if (status instanceof A) { console.log('inside A') } else i ...

Once an ng-repeat is completed, I must extract and retrieve the 'id' of a specific element

Is it possible to retrieve the 'id' of the comment I'm replying to and save it for an Ajax call? I can easily access other data with ng-model, but using value="{{this.id}}" in a hidden input doesn't seem to work like in JQuery. <scr ...

Displaying a div on the click of an image within a for loop using JavaScript

Currently, my website has a blog page that only showcases each individual blog post's photo and title. This is achieved through the use of a FOR loop (shown below). I am interested in implementing a feature where clicking on a blog post's photo o ...

Utilizing a c++ xpcom component in conjunction with a javascript xpcom component

After developing an XPCOM component using C++ with a GetHWND() method, I am now working on another XPCOM component using JavaScript. My goal is to utilize the GetHWND function from my C++ component in the JavaScript XPCOM component. Here is the code snippe ...

Decoding HTML with Python

My current project involves creating a program that can find the definition of any given word and return it. I managed to achieve this using RegEx to search for text between specific tags where the definitions are stored. However, I am now seeking a more ...