Enter the text div that has been chosen

I have a mini question regarding how to select text and place it in a selected div.

This demo was created from codepen.io.

In this demo, you will see a blue button and text in a textarea. I would like to be able to select the text "Select this text", click the blue button, and have the selected text transformed into

<div class="selected">Select this text.</div>
.

Can someone assist me with this? Thanks!

$(document).ready(function() {
  $("body").on("click", ".Bold", function() {
    // Code goes here...
  });
});
html,
body {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
  font-family: helvetica, arial, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  background-color: #fafafa;
}
.container {
  position: relative;
  width: 100%;
  max-width: 500px;
  margin: 0px auto;
  margin-top: 30px;
}
.editor {
  float: left;
  width: 100%;
  padding: 30px;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
}
.editButtons {
  width: 100%;
  float: left;
  margin-bottom: 15px;
}
.Bold {
  padding: 5px;
  border-radius: 3px;
  -webkit-border-radius: 3px;
  background-color: blue;
  position: relative;
  max-width: 150px;
  text-align: center;
  color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="editButtons">
    <div class="Bold">Add in Div</div>
  </div>
  <textarea class="editor" id="editor">Select this text. and click blue button. It should be add the following div tag like this:
    <div class="selected">Select this text.</div>
  </textarea>
</div>

Answer №1

Are you seeking the solution below?

$(document).ready(function() {
   $("#btnSelect").click(function() {
      var $area = $("textarea.editor");
      var area = $area.get()[0];
      var s = area.selectionStart;
      var e = area.selectionEnd;
      if (s == e) return;
      var text = $area.val();
      var before = s > 0 ? text.substr(0, s) : "";
      var selection = text.substr(s, e - s);
      var after = e < text.length - 1 ? text.substr(e) : "";
      
      selection = "<div id=\"selected\">" + selection + "</div>";
      $area.val(before + selection + after);
      return false;
   });
});
html,
body {
   width: 100%;
   height: 100%;
   padding: 0px;
   margin: 0px;
   font-family: helvetica, arial, sans-serif;
   -moz-osx-font-smoothing: grayscale;
   -webkit-font-smoothing: antialiased;
   background-color: #fafafa;
}

.container {
   position: relative;
   width: 100%;
   max-width: 500px;
   margin: 0px auto;
   margin-top: 30px;
}

.editor {
   float: left;
   width: 100%;
   padding: 30px;
   box-sizing: border-box;
   -webkit-box-sizing: border-box;
}

.editButtons {
   width: 100%;
   float: left;
   margin-bottom: 15px;
}

.editButtons a {
   text-decoration: none
}

#btnSelect {
   padding: 5px;
   border-radius: 3px;
   -webkit-border-radius: 3px;
   background-color: blue;
   position: relative;
   max-width: 150px;
   text-align: center;
   color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
   <div class="editButtons">
      <a href="" id="btnSelect">Select</a>
   </div>
   <textarea class="editor" id="editor">Select this text. and click blue button. It should be add the following div tag like this: <div class="selected">Select this text.</div> </textarea>
</div>

Answer №2

$(document).ready(function() {
    $("body").on("click",".Bold", function(){
        var textField = $('#editor');
        var start = textField[0].selectionStart;
        var end = textField[0].selectionEnd;
        var textValue = textField.val();
        var selectedText = '<div class="selected">' + textValue.substring(start, end) + '</div>';
        var finalText = textField.val().substring(0, start) + selectedText + textField.val().substring(end, textValue.length);
        textField.val(finalText);
    });
});

Answer №3

$(document).ready(function() {
  $("body").on("click", ".Bold", function() {
    // Implement your code here...
    $('.Bold').html('<div class="selected">Highlight this text.</div>')
  });
});
html,
body {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
  font-family: helvetica, arial, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  background-color: #fafafa;
}
.container {
  position: relative;
  width: 100%;
  max-width: 500px;
  margin: 0px auto;
  margin-top: 30px;
}
.editor {
  float: left;
  width: 100%;
  padding: 30px;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
}
.editButtons {
  width: 100%;
  float: left;
  margin-bottom: 15px;
}
.Bold {
  padding: 5px;
  border-radius: 3px;
  -webkit-border-radius: 3px;
  background-color: blue;
  position: relative;
  max-width: 150px;
  text-align: center;
  color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="editButtons">
    <div class="Bold">Click to Highlight</div>
  </div>
  <textarea class="editor" id="editor">Click the blue button after selecting this text. It will add the following div tag as shown below:
    <div class="selected">Highlight this text.</div>
  </textarea>
</div>

Answer №4

$(document).ready(function() {
  $("body").on("click", ".Bold", function() {
    // Custom code can be inserted here...
    $(this).html('<div class="highlighted">Click here to highlight this text.</div>')
  });
});

Give it a shot!

Answer №5

It seems that there may be some confusion. Are you trying to apply a class named selected to the textarea element? If so, here is the correct way to achieve that:

$(document).ready(function() {
   $(".Bold").on("click", function(){
      $('textarea').addClass('selected');
   });
});

.selected {
   background: black;
   color: white;
}

Answer №6

Give this a try - Perhaps you're looking to display the text that has been selected?

$("body").on("mousedown", ".Bold", function() {
  $('.container').append('<div class="selected">' + window.getSelection().toString() + '</div>');
  console.log('<div class="selected">' + window.getSelection().toString() + '</div>');
});
html,
body {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
  font-family: helvetica, arial, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  background-color: #fafafa;
}
.container {
  position: relative;
  width: 100%;
  max-width: 500px;
  margin: 0px auto;
  margin-top: 30px;
}
.editor {
  float: left;
  width: 100%;
  padding: 30px;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
}
.editButtons {
  width: 100%;
  float: left;
  margin-bottom: 15px;
}
.Bold {
  padding: 5px;
  border-radius: 3px;
  -webkit-border-radius: 3px;
  background-color: blue;
  position: relative;
  max-width: 150px;
  text-align: center;
  color: #ffffff;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="editButtons">
    <div class="Bold">Add in Div</div>
  </div>
  <textarea class="editor" id="editor">Select this text. and click blue button. It should be add the following div tag like this:
    <div class="selected">Select this text.</div>
  </textarea>
</div>

Answer №7

Here is an alternative solution that you may find useful:

function displaySelectedText() {
  var textArea = document.getElementById("text");
  var selectedText = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart);
  alert(selectedText);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="displaySelectedText()" value="Select text and click here" />

I hope this solution meets your needs!

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

Vue.js component unable to validate HTML input patterns

Attempting to create HTML forms with the 'pattern' input attribute has been an interesting challenge for me. When implementing this through Vue.js components, I encountered some strange behavior. Check out this fiddle to see it in action. Vue.co ...

Having trouble loading CSS and JavaScript files in CodeIgniter version 3.0.4?

I am facing an issue with loading my CSS and JS files in the view file. I have already added them to the folder and set the base URL. These codes were working fine with a project I previously did on an older version of CodeIgniter. What could be causing ...

The mysterious height phenomenon when setting the width of a list item with jQuery

Consider a basic ul and li setup similar to this: <div id="middle"> <ul> <li> <a> bridal </a> </li> //.... </ul> </div ...

Is it possible to string together requests in a Vue method?

Whenever a user clicks on a specific button, a request is sent to the server and an answer is received. If the user clicks on this button 100 times, I want to send 100 consecutive requests to the server. Each request must be sent after the previous one, as ...

Increase the background image size for a <li> element

I am working with an unordered list and have set it up to display a background image on the li element when the cursor hovers over it: <div class="sidebar"> <ul> <li>test</li> <li>test</li> ...

Creating intricate filters using React's map functionality

QUESTION HAS BEEN UPDATED. I am currently working on implementing a filter for my map, allowing users to specify which options they want to view using multiple selection boxes. However, I am encountering an issue with the page that appears after the user ...

Troubleshooting: jQuery ajax form is not functioning as expected

After attempting various methods to create a basic jQuery Ajax form, I am puzzled as to why it is not submitting or displaying any notifications. Below is the code I have been working with: Javascript ... <script type="text/javascript" src="assets/js ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

The functionality of an AJAX poll is not functioning properly due to issues with the PHP

I am embarking on my first website and project, hoping to see it through to completion. In my room, I have a modest site set up on a Raspberry Pi 2. Users visit this site to cast their votes of 'yes' or 'no'. However, there seems to be ...

Creating line breaks in Bootstrap input group formatting

My issue involves rows with checkboxes and labels, some of which are longer than others. When the browser is resized or viewed on a mobile device, the columns containing longer labels collapse to a second row while shorter labels stay beside their checkbox ...

Angular 6 - Setting up radio buttons with Bootstraps

I am currently implementing Bootstrap's radio buttons functionality in my Angular 6 project. When using a button group, the active state should switch to the clicked button every time a different button is clicked. If this is confusing to understand, ...

Display content in two columns. If the width of the left column is too narrow, move the content in the right column

In my layout, there is a wrapper div with two child elements: left div and right div. The left div contains text which can be lengthy, while the right div holds an image loaded asynchronously without known width: <div id="wrapper"> <div id="l ...

Unable to modify the default Nuxt favicon

Just getting started with Nuxt and attempting to update the default favicon for my project. I swapped out the favicon.png and favicon.ico files in my static directory, but unfortunately, it didn't take effect. Next, I tried replacing the favicon.png ...

What is the best way to successfully send an object through AJAX once all its updates are completed?

I am experiencing an issue with my JavaScript code within an event: var userData = tableWidget.grid('userData'); console.log(tableWidget.grid('userData')); $.ajax({ "url": "../../server/query.aspx?tableEvent=reordercolumns&tabl ...

Arranging items to be flush at the base of several columns

I need help with positioning buttons at the bottom of three columns of text. I want them to be aligned vertically on the page when the columns are side-by-side, and then placed after each column when viewed in a single-column layout on small screens. The c ...

Steps to customize the default thumbnail image of an embedded video that is not from YouTube

I've added a video to an HTML page. Here is the code: <div> <video width="400" controls> <source src="videos/myvideo.mp4" type="video/mp4"> </video> </div> Is there a way to modify the default thumbnail image of ...

Having trouble with my code trying to transfer elements back and forth between two unordered lists using an "addEventListener"

I have developed a task management system where users can create a to-do list for their daily tasks. Upon completion of a task, they can tick the checkbox next to it, which will trigger a strikethrough effect. The completed tasks are then moved from the "u ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

The input box is not properly filled with the complete string using protractor sendKeys

[HTTP] --> POST /wd/hub/session/ffcd7072-9f96-45cb-a61d-ec53fc696b56/element/0.9513211246393813-32/value {"value":["1","0","0","0","1"],"text":"10001"} My JavaScript code snippet: this.zipcode = element(by.model('personalInfo.zipcode')); t ...

The code function appears to be malfunctioning within the Cordova platform

When working with Cordova, I encountered an issue where I needed to trigger a button event from a listener. In my app, I am loading a specific page . This page contains a button with the class name "btn", and I wanted to display an alert when that button i ...