I'm looking to utilize this script to generate multiple buttons that insert content into a textarea. How can

Finally, I stumbled upon a script that enables undo/redo functionality for programmatically inserted text. You can find it here.

If you want to check out the original script demo, click here.

Here is the initial script:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// http://stackoverflow.com/a/9851769/529024
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
...
textarea {
  padding: 10px;
  font-family: Calibri;
  ...
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name='textArea' class='textArea' rows="7" cols="50">Suspendisse convallis, metus ... viverra condimentum, neque neque tincidunt diam, nec vestibulum neque nisi...

Answer №1

The issue you are facing is that both textAreas have the same 'id' which is 'codearea1'

If I understood your question correctly, you have a total of 80 textAreas and buttons. Each button should fill a specific textArea when clicked. Therefore, it is important to assign a unique 'id' to each textArea similar to how you have done for buttons.

If I were in your shoes, I would simplify the code further by assigning attributes like 'class' and 'id' to each button, as well as an 'id' to each textArea with mapping in the JavaScript.

For example:

In HTML:

<div id='n101' class="fillTextBtn">n101 button</div>
 <div id='n102' class="fillTextBtn">n102 button</div>

In JavaScript:

<script>

    var mapObj = {
       'n101': 'text1',
       'n102': 'text2'
    }

    jQuery(".fillTextBtn").on("click", function(event) {
       var currButtonId = jQuery(event.target).attr('id');
       var mappedText = mapObj[currButtonId];

       jQuery("#codearea1").focus();
       document.execCommand('insertText', false, mappedText);
    });
</script>

This approach eliminates the need to separately bind events to each button and simplifies other operations as well. It avoids repetitive code.

I hope this explanation helps you streamline your code.

Fiddle: https://jsfiddle.net/q6rugcvb/

Update:

The current behavior is due to the fact that the first script tag sets 'text' as 'text1' while the second script tag sets 'text' as 'text2'.

Therefore, when you click on a button, 'text' becomes 'text2'.

To achieve the desired result, simply include this line inside your click function:

var text = 'text1';

For instance:

 jQuery("#n101").on("click", function() {
     var text = 'text1';

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

Creating a UI Component when clicking on something

Currently, I am immersed in a project and had a question regarding the possibility of rendering UI components on click. In other words, is it feasible to trigger component rendering through an onclick event? For instance, consider the following example: & ...

Comparing PHP's STRCHR with the equivalent function in JavaScript

Does anyone know if there is a similar function in JavaScript to strchr in PHP? I could use some assistance. Thank you! ...

Forming a ring around a character within a header one element

I am faced with the challenge of only circling a single letter within a word that is contained in an H1 tag. While creating a circle around text is easy, I specifically need to target just one letter: .large { font-size: 5em; } .circle { border-rad ...

Create a line graph overlaying an area chart

I am currently working on developing a chart using D3js v5.12.0. So far, I have successfully created an area chart with the year variable on the X-axis and the earth_footprint variable on the Y-axis. You can find the data for this chart at the following ...

The interaction between MVC Razor and JQuery while utilizing a data table encounters an Uncaught TypeError: the undefined element is

I need some assistance with a jQuery DataTable issue that I've encountered. Whenever I try to call the function $ ('#tablaUsuarios').dataTable(), I get an error message saying "Uncaught TypeError: undefined is not a function". @Styles.Rend ...

Struggling to prevent keyboard-triggered date changes in the MUI DatePicker API

Link to CodePen: codepen.io/s/jk3sgj?file=/demo.tsx Is there a way to prevent users from manually typing in dates and force them to select a date from a modal picker instead? I tried using the ReadOnly prop, but it disabled the entire input field, includ ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

After the reconnect, the `socketInstanceRef.current.readyState` transitions to 3 and does not render any other components

Essentially, I am utilizing a custom hook called connect.ts to optimize a single socket connection instead of creating new connections each time a message needs to be sent from anywhere within my app. I have also implemented reconnection logic in this hoo ...

What are some methods to improve the performance of this jQuery-powered webpage?

I've developed a contact script that leverages jQuery for ajax requests and animations. However, the sluggish aspect arises when using a hashchange plugin to improve the functionality of the back button. Upon completing the animation for the 'f ...

Node 14 introduces a new feature that allows modules to be imported using absolute paths for native ES6 modules

As I develop an app in node version 14.9.0, the need for importing modules arises. To make the process cleaner and more organized, I have configured my ES6 module with "type": "module" in my package.json. My goal is to implement absolut ...

Ways to incorporate AngularJS variable within a JavaScript function

My current task involves iterating through a JSON file using AngularJS. Below is the function that I am working with: <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script> functi ...

Problems arising from positioning elements with CSS and organizing list items

I've been working on creating a navigation sidebar using Angular and Bootstrap, but I'm having trouble getting my navigation items to display correctly. APP Component HTML <div class="container-fluid"> <div class="row" id="header"&g ...

Header position displays incorrectly in Internet Explorer due to CSS

I'm experiencing an issue with the header position on my website, as it always aligns to the left side in IE. However, in Chrome and Firefox, it is perfectly centered without any problems. Can anyone offer their expertise on how to resolve this? Hom ...

Error encountered in Internet Explorer 11 - Access is forbidden - XMLHttpRequest

I am encountering a unique issue with IE11 and ajax. Most of the time, everything works as expected when I use the code below for my requests. However, I have noticed that when I try to use it in combination with a copy and paste function, an 'Access ...

The error message states: `discord.js TypeError: Unable to access the property 'resolve' as it is undefined`

Encountering an issue with the following code snippet const Discord = require('discord.js'); module.exports = { name: 'info', description: "Shows BOT's Informations", execute(message, client, args) { c ...

Refresh database using ajax requests

Looking for assistance to update my database with a dropdown menu using ajax. Most examples I've seen involve retrieving data rather than updating it. Can someone please provide guidance? The code in my php updatestatus.php page is as follows: inclu ...

Measuring JSON data with PHP through asynchronous requests

Looking to retrieve a specific count from a json dataset. Here is an example json format: { "tickets": [ { "url": "https://asd.zendesk.com/api/v2/tickets/1.json", "id": 1, "external_id": null, "via": { "channel": "sa ...

Error: Property 'html' is undefined - AJAX response must be displayed only in a specific div

I encountered an issue: Uncaught TypeError: Cannot read property 'html' of undefined I am working on implementing a voting system for each video on my webpage from a database. I have successfully integrated it using AJAX, but the problem is ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...

Creating websites with HTML and CSS

I am trying to enhance the style of my paragraph by applying multiple attributes, such as font color and font type, using CSS. While applying a single attribute like p {color:green} works fine, I encounter errors when trying to apply more than one line of ...