How can I avoid using the appendTo method in jQuery?

There seems to be an issue in my HTML code, could you please take a look at the code snippet below:

HTML:

<div class="agent_select_wrap">
    <select name="menu-114" class="wpcf7-form-control wpcf7-select" aria-invalid="false">
        <option value="Select Category" selected="selected">Select Agent Name</option>
        <option>Mr. abc</option>
        <option>Mr. abc</option>
        <option>Mr. abc</option>
    </select>
</div>
<div class="agent_select_wrap02">
    <div class="my_textarea"></div>
    <button>Send</button>
</div>

CSS

.agent_select_wrap {  width: 40%; margin: 30px auto 10px auto;}
.agent_select_wrap02 {  width: 40%; margin: 0px auto 50px auto;}
.agent_select_wrap select{font-weight:100; font-family: 'Open Sans', sans-serif; font-size: 13px; color: #494949; background: #fff url('../images/selectbox-arrow02.png') right center no-repeat; outline: 0; margin-bottom: 0px; margin: auto; width: 100%; height: 40px; border: 1px solid #ccc; border-radius: 0; -webkit-appearance: none; -moz-appearance: none; appearance: none; -ms-appearance: none;  /*box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.25);*/}
.agent_select_wrap select option { background: #fff; color: #000;}
.my_textarea textarea {font-weight:100; font-family: 'Open Sans', sans-serif; font-size: 13px; color: #494949; width:97.4%; display:block;   height: 100px; border: 1px solid #ccc; padding: 6px 0 0 6px; margin: 0; border-radius: 0px;  /*box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.25);*/}
.my_textarea p{padding: 0; margin: 0; text-align: center; font-size: 12px;font-family: 'Open Sans', sans-serif;}
.agent_select_wrap02 button {  display: block; margin: 16px auto 0 auto; padding: 7px 30px; background: #494949; color: #fff; font-weight: 100; font-family: 'Open Sans', sans-serif; font-size: 18px; border: 0;}
.agent_select_wrap02 button:hover {cursor:pointer;}

JS

$(document).on('change', 'select[name=menu-114]', function () {
    $("<textarea> Hello Mr. </textarea>").appendTo(".my_textarea")
    $("<p>Please enter your message here..!</p>").appendTo(".my_textarea")

    $(function () {
        $('select').change(function () {
            $that = $(this);
            $('textarea').val(function () {
                return $(this).prop('defaultValue') + ' ' + $that.val();
            });
        });
    });
});

Check out the live example here: https://jsfiddle.net/7j623eho/

Answer №1

Make a simple tweak to just one line in your JavaScript code.

$(".my_textarea").html("<textarea> Hello there! </textarea><p>Feel free to type your message here..!</p>");

Replace your current code with the one provided above.

$("<textarea> Hello there! </textarea>").appendTo(".my_textarea")
$("<p>Feel free to type your message here..!</p>").appendTo(".my_textarea")

Answer №2

It seems like the issue may be that you are not properly removing the newly created textarea. One solution could be to create the textarea inside a <div id='temp'> element and then remove this element before creating a new one.

$('#temp').remove();

var container = $('<div id="temp">');
$("<textarea> Hello there! </textarea>").appendTo(container);
$("<p>Feel free to write your message here..!</p>").appendTo(container);
container.appendTo(".my_textarea");

Answer №3

If you are looking to create the textarea just once and have the inline handler manage any further changes, one way to accomplish this is:

var onMenuSelected = function () {
    $("<textarea> Hello Mr. </textarea>").appendTo(".my_textarea")
    $("<p>Please enter your message here..!</p>").appendTo(".my_textarea")

    $(function () {
        $('select').change(function () {
            $that = $(this);
            console.log('Select');
            $('textarea').val(function () {
                return $(this).prop('defaultValue') + ' ' + $that.val();
            });
        });
    });

    // Just unbind self
    $(document).off('change', 'select[name=menu-114]', onMenuSelected);
}
$(document).on('change', 'select[name=menu-114]', onMenuSelected);

By defining the function, you can easily remove the $(document).on without affecting other handlers that may exist. This ensures that the select event is only registered once.

Check out the jsFiddle link here.

Answer №4

Let's get started, here is the code snippet to use:

HTML

<div class="agent_select_wrap">
                     <select name="menu-114" class="wpcf7-form-control wpcf7-select" aria-invalid="false">
                        <option value="Select Category" selected="selected">Select Agent Name</option>
                                <option>Mr. abc</option>
                                <option>Mr. abc</option>
                                <option>Mr. abc</option>
                     </select>                    
                </div>




                <div class="agent_select_wrap02">

                    <div id="my_textarea0">

                    </div>
                    <textarea id="my_textarea">

                    </textarea>
                    <button>Send</button>
                </div>

JS

$(document).on('change', 'select[name=menu-114]', function () {
    $("#my_textarea0").html("<textarea> Hello Mr. </textarea>")
    $("#my_textarea").html("<p>Please enter your message here..!</p>")

    $(function () {
        $('select').change(function () {
            $that = $(this);
            $('textarea').val(function () {
                return $(this).prop('defaultValue') + ' ' + $that.val();
            });
        });
    });
});

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

The website shifts as you navigate to a new page

Could use some insight on an issue with my website . Whenever I navigate to a different page, like the "Rules" page from the main site, the container seems to shift down slightly. Any ideas on what could be causing this? I've been struggling to pinpoi ...

send a variable to a function in a random sequence

In my code, I have a function defined as follows: let showNotification = function(a,b,c,d,e,f){ console.log(a,b,c,d,e,f); } When calling this function, it is crucial to pass parameters in the correct order. For example, if I want to omit values for c, ...

The custom switch input with a blue outline is reluctant to vanish

Hey there! I'm currently using Bootstrap and I'm facing an issue with removing the blue outline around a custom switch button when clicked. I've tried to remove it using CSS but it doesn't seem to work, especially in Chrome. Here's ...

Tips for organizing dynamic table data following an append operation

Hey there! I'm currently working on a project involving sorting students after applying filters. Once the students have been filtered, I need to append classes and text to buttons as shown in the image below: https://i.stack.imgur.com/c9Mtm.png The HT ...

extract all elements from an array nested within another array

I am having difficulty extracting data from an array file in PHP. I was able to read it and convert it into a PHP array, but now I want to display the stored information in a table, however, I keep getting incorrect values. How can I retrieve the informat ...

Troubleshooting: Ngx-Echarts Animation Issue at Startup

I've been working on integrating ngx echarts into my Angular app, but I'm facing an issue with the animation during the initial load of the chart. Take a look at this Stackblitz example where you can see that the bars render quickly on initial lo ...

Having trouble inserting a Button element into a li parent element

I'm attempting to insert a button inside an li element using the .appendChild method, but for some reason, it's not working. I also tried changing the parent's inner HTML. let inputElement = document.querySelector('#input'); let ...

I'm having trouble getting the app.locals function within a button to work on my EJS template. Can anyone help troub

Below is the content of my script named agents.js: var express = require('express'); var router = express.Router(); var app = express(); // Is it appropriate to call Express like this twice? router.get('/', function(req, res, next) { ...

The Bootstrap carousel feature allows you to track the duration each image is displayed

Is there a way to track the amount of time a specific image is visible to the user in a Bootstrap 5 carousel? I'm interested in measuring how long a user views a particular image, such as a product image, in the carousel. For example, I'm lookin ...

Why do HTML elements in an email have strange prefixes added to their IDs?

Currently, I am working on setting up automated tests for my service that automatically sends email reports. The objective is to verify the accuracy of data in the emails. To accomplish this, I have started assigning unique IDs to different HTML elements ...

Tips for updating the display by fetching data from a database through a websocket

I am looking for a solution to update a specific part of my webpage without having to refresh the entire content. On my index.html page, I have three panels displaying various ticket statuses. I want to automatically update the number of resolved tickets s ...

What is the best way to show only a specific v-for element in Vue.js?

Is there a way to select a specific item from a v-for loop in vue js? I am using v-for to retrieve Youtube data API items. Each item contains an iframe that should only be displayed when a user clicks on a play button. Currently, all the iframes are shown ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

How do I easily show/hide a submenu in AngularJS with a toggle menu?

After browsing some Stacks, I've come to the realization that I need to create separate directives in order to hide or toggle a menu from its sub-menu items. I want the menu to be hidden when any of the sub-menu items are clicked. However, I can&apo ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Exploring the file attributes within nw.js

I'm in the process of developing a native application using nw.js. I have included the following code snippet: <input id="fileDialog" type="file" accept=".pdf,.epub" multiple/><a id="add" href="#">Add</a> Below is my JavaScript cod ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Refresh the DIV element that houses dynamically generated <ul> HTML content after submitting new inputs

UPDATE: After delving into the code of nested include files in the child PHP file, I've identified conflicts with the parent PHP include files. This means that the child PHP file/div relies on the parent being refreshed, preventing me from refreshing ...