A guide on showcasing items on an html webpage through the use of javascript

Currently, I have a series of hardcoded HTML elements in my code snippet.

                    <!-- Reciever Message-->
                <div class="media w-50 ml-auto mb-3">
                    <div class="media-body">
                        <div class="bg-primary rounded py-2 px-3 mb-2"> 
                            <p class="text-small mb-0 text-white">Test chat</p>
                        </div>
                    </div>
                </div>

My aim is to dynamically generate these elements when a button is clicked and insert the text entered into the input box into the <p> tag. Here's the code for the button and input box:

<form action="#" class="bg-light">
                <div class="input-group">
                    <input type="text" placeholder="Type a message" aria-describedby="button-addon2" class="form-control rounded-0 border-0 py-4" id="message">
                    <div class="input-group-append">
                        <button id="button-addon2" type="submit" class="btn btn-link" onclick="addText()"> <i class="fa fa-paper-plane"></i></button>
                    </div>
                </div>
            </form>

Here is the function that should be executed upon clicking the button:

function addText() {
    var p = document.createElement("p");
    p.className ="text-small mb-0 text-white"
    var inputValue = document.getElementById("message").value;
    var text = document.createTextNode(inputValue);
    p.appendChild(text);

    if (inputValue === '') {
        alert("You must write something!");
    } else {
        var div = document.createElement("div");
        div.className = "media w-50 ml-auto mb-3";
        var div2 = document.createElement("div");
        div2.className = "media-body";
        var div3 = document.createElement("div");
        div3.className = "bg-primary rounded py-2 px-3 mb-2";
        div3.id = "receive-text";
        div3.appendChild(p);
    }
    document.getElementById("message").value = "";
}

However, after clicking the button, nothing happens. What am I doing incorrectly?

Answer №1

After some adjustments to the code, I managed to achieve the expected outcome

function updateText() {
  var para = document.createElement('p');
  para.className = 'text-small mb-0 text-white';
  var userInput = document.getElementById('input').value;
  var newText = document.createTextNode(userInput);
  para.appendChild(newText);

  if (userInput === '') {
    alert('Please enter some text!');
  } else {
    var newDiv = document.createElement('div');
    newDiv.className = 'media w-50 ml-auto mb-3';
    var innerDiv = document.createElement('div');
    innerDiv.className = 'media-body';
    newDiv.appendChild(innerDiv);
    var contentDiv = document.createElement('div');
    contentDiv.className = 'bg-primary rounded py-2 px-3 mb-2';
    contentDiv.id = 'new-text';
    innerDiv.appendChild(contentDiv);
    contentDiv.appendChild(para);
    document.body.appendChild(newDiv);
  }
  document.getElementById('input').value = '';
}

The issue was simply not using appendChild. Once added, everything worked correctly.

Answer №2

It appears that you have created a variable named div3 and included the p element within it, but I do not see where you are adding them to the document.

To add them, you can use the following code:

document.body.appendChild(div3)

or

document.getElementById("#idOfDiv3Parentelement").appendChild(div3)

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

Launch the sidebar window using jQuery

I've been attempting to create something similar to this. However, I'm having trouble replicating it exactly. What I've attempted I've managed to create a replica, but the issue is that the buttons are fixed. Could setting the left ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

Invoke a jQuery function in the parent page using regular JavaScript from an iframe

I have successfully created an iframe using regular javascript. Inside the iframe is a Jquery function along with JQuery itself and it functions correctly within the iframe. However, I am now looking to execute this function from the parent page instead of ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

How can you attach an event handler to an HTML button without disrupting its default behavior?

I am working on enhancing a contact form to include a feature where the submit button becomes disabled for five seconds after it is clicked. This is to prevent accidental repeat submissions from occurring. However, I am facing an issue where disabling the ...

Alignment in the vertical direction of two lines

I've been struggling to align some HTML elements visually the way I want. There are two lines of text followed by a link. I'm trying to get the link to be vertically centered between the two lines, rather than just after the second line. Using a ...

Updating existing text to create personalized HTML dropdown menus

I have designed a unique set of dropdowns by using divs and checkboxes instead of the traditional elements My goal is to dynamically change the 'select-wrapper--title' text (e.g. the first option) based on the selected option in the dropdown I ...

The mousedown event handler in Three.js disrupts the focus on the input field

Here is a line of code in threejs: document.addEventListener('mousedown', onDocumentMouseDown, false); This particular code snippet causes the input field to lose focus when clicked. This can be problematic, for instance, when there is a canva ...

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

Dygraphs: Utilizing two y-axes in a single series

I'm interested in plotting a single series with two synchronized y-axes that display different units, such as °F and °C temperatures. I want the data to be readable from both axes, but only one set of points should be plotted. Here are some approac ...

Tips for automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

What is the best way to update a targeted component in React when triggered by an event handler?

Your goal may seem straightforward, but getting a reference to a specific component using this is proving to be tricky. Here we have our App.js file: import React, { Component } from 'react'; import CoolBox from './coolBox.js'; import ...

The disabled functionality of AddCircleIcon in Material UI seems to be malfunctioning

The AddCircleIcon button's disabled functionality is not working, even though the onClick function is functioning properly. Even when directly passing true to the disabled property, it still doesn't work. I am in need of assistance to resolve thi ...

The image wrapping feature within a div element will only function properly when there are more than one line of text present

I have come across a strange issue that I am struggling to solve. I have an image within a div with the float: left; attribute, but this styling only seems to work when the div has more than one line of text. When the div contains just one line, it ends ...

The outcomes may vary even with identical fonts, character spacing, and line-height

When I first learned about @font-face in CSS3, I was excited about the prospect of using consistent fonts across all browsers. However, after experimenting with it using the code below on jsFiddle, my expectations were challenged: HTML: <div> T ...

Using linear-gradient() in the border-image property does not actually generate a border

I am attempting to add a linear gradient border around a dynamically created div using JavaScript. However, I am not seeing the border show up as expected and it is not displaying in black. Check out my code snippet below: const devlogList = document.cre ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

monitoring the HTML code post-editing

After using jQuery, I made modifications to the HTML source code by adding several text fields. However, when I check the page source in Google Chrome, it still shows the original source code. Is there a method to view the updated HTML code? ...

Ways to retrieve the ID attribute value of the third ancestor above

How can I retrieve the ID attribute of the 3rd parent element when a link is clicked? Take for example: <div id="First Div"> <div class="class A"> <div class="class B"></div> <div class="class C"></div> &l ...