Interactive messaging input field

I am having trouble figuring out how to incorporate a jQuery command that will display the entered message in the chat body when the user presses the enter key. I want the message to be formatted in a 'msg_b' style. I attempted using the following code, but it did not work:

$('textarea').keypress(function(e){
    if(e.keyCode==13){
      var msg=$(this).val();
      $this.val("");
      $("<div class='msg_b'>"+msg+"</div>").insertBefore('.msg_insert');
    }
  });

Here is an excerpt from my HTML script:

<div class="msg_head">Rishabh Sood
    <div class="close"> x </div>
  </div>

  <div class ="msg_wrap">
    <div class ="msg_body">
      <div class ="msg_a">Hey bro wassup!</div>
      <div class ="msg_b">All nice!</div>
      <div class="msg_insert"></div>
    </div>

    <div class="msg_footer"><textarea class="msg_input" rows="4" placeholder = "Enter Message"></textarea></div>
  </div>

Answer №1

Make sure your HTML code matches the following structure:

<body>
<div class="msg_head">John Doe
  <div class="close"> x </div>
</div>
<div class="msg_wrap">
  <div class="msg_body">
    <div class="msg_a">Hello there!</div>
    <div class="msg_b">Hi, how are you?</div>
    <div class="msg_insert"></div>
  </div>
  <div class="msg_footer">
    <textarea id="commentTxt" class="msg_input" rows="4" placeholder="Enter Message"></textarea>
  </div>
</div>
 <script src="script.js"></script>

Here is an example of what your 'script.js' file should look like:

 $('#commentTxt').keypress(
        function(e){
        if(e.keyCode==13){
        var msg=$(this).val();
        $("<div class='msg_b'>"+msg+"</div>").insertBefore('.msg_insert');
        }
        });

You can view and test this code on Plunker here

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

Adjust the height of a div to match the tallest element in the same row using jQuery and Javascript

I need to display multiple rows of products, each row containing 4 products. The code snippet below shows an example with only 1 product. To create a row with 4 products, the code for <div class='col-xs-6 col-sm-3 col-md-3'> needs to be rep ...

JQuery functionality not functioning properly following an AJAX page reload

Currently, I am utilizing a jQuery code to select all checkboxes in the following manner: var JQ7=jQuery.noConflict(); JQ7(document).ready(function(){ JQ7("#chkAll").click(function(){ JQ7(".chk").prop("checked",JQ7("#chkAll").prop("checked")) }) }); ...

Is it possible to adjust a CSS value once a JS value hits a specific threshold?

Currently, I am developing a web game where the website displays different emotions, including anger. I have successfully implemented the anger level internal coding and I am now focusing on adding a color-changing feature when the anger level reaches a sp ...

Attempting to adapt the "ptflickrgallery" jQuery plugin to automatically retrieve Flickr Photosets

I found a great plugin at that meets my needs for displaying Flickr albums and photos with slideshow options, thumbnails, and more. However, I'm struggling to automate the input of Photoset IDs. I've been experimenting with the jQuery.flickrGal ...

Tooltips experience issues when interacting with elements that do not utilize the :active state

$(function () { $('[data-toggle="tooltip"]').tooltip() }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" ...

Iterating through JSON array objects using JQuery's $.each() method

I'm struggling with solving a JQuery $.each() iteration and need some help. Here is an example of my array, trimmed for convenience: [{"GROUP_ID":"143", "GROUP_TYPE":"2011 Season", "EVENTS":[ {"EVENT_ID":"374","SHORT_DESC":"Wake Forest"}, ...

How can I apply the "active" class to a standard header?

source: header.php <?php $currentPage = basename($_SERVER['PHP_SELF']); echo $currentPage; ?> <div class="nav-links"> <nav class="navbar navbar-inverse"> <div class="container"> <div c ...

When hovering over an image, another image is revealed

<div> <a href="#"><img src="images/Informasjon_button.png" width="120px" height="120px" /></a> </div> <div> <a href="#"><img src="images/Mail_button.png" width="120px" height="120px" /></a> </div ...

Is there a way to ensure that the number value on the progress bar remains centered and at the top position

I am currently working on a project that involves progress bars showing real-time values. However, I am facing an issue where the number value is not staying centered within the bar and instead getting pushed ahead of the blue fill, disappearing when it re ...

Restrict the child's height to the remaining space within the parent container

I'm attempting to divide the viewport's height between two divs. In the top div, there is a small div followed by a larger div that should scroll if it doesn't fit within the remaining space of the parent div. Below is the structure of my HT ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

Experiencing issues on Chrome while switching stylesheets; any tips on avoiding this glitch?

I am currently working on designing a webpage and running into some issues with Chrome when changing stylesheets for light and dark themes. Initially, I have included this <link>: <link rel="stylesheet" href="/css/dark.css" id="theme"> To sw ...

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Switch out a section of the web address with the information from the button to

Before we begin: Check out this Fiddle My current goal is to create a functionality where clicking a button will replace the # in a given link with the text entered in a text box, and then redirect the user to that modified link. http://www.twitch.tv/#/ ...

Z-index ordering for menus containing submenus

I'm trying to create a menu with animated submenus that slide in from the left side of the page. However, no matter what z-index I assign to my submenu, it always appears on top of my content. I positioned my submenu 150px to the left to show the over ...

Inserting a Div Element into a List Using a User-Entered Variable (jQuery)

For a school project, I am currently working on a task involving multiple "Add Task" buttons with prompts that appear when clicked. The goal is to have the entered item added to the bottom of the corresponding list. I have experimented with options like a ...

Find an element contained within a specific frame

Here is the HTML code I am working with: <td class="gnb_menu" id="MAIN_04" name="MAIN_04" style="width:100px;text-align:center;"> <span style="cursor:pointer;" onclick="javascript:movePage('MAIN_04','/basis/menuServlet.do?m ...

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

Function that activates traffic lights

Currently, I'm encountering errors while working on this project in Notepad. Can you help me figure out what's wrong with my code? I'm attempting to create an onload traffic light using an object array. The requirement is to implement this f ...

Is there a quicker way to reference the same post on jQuery?

I am looking to automatically start the same ajax request once it finishes. The reason behind this is that using setInterval does not guarantee that all requests made in the first second will be completed before the second setInterval call. I have explore ...