Attempting to reveal various input values by selecting different buttons on a single page

My goal is to comment on each blog post on a page. However, I am having trouble with the JavaScript code to get all buttons and input fields working and displaying the input values.

This is my current JS code: I am attempting to iterate through each button and retrieve the corresponding input value. I have also tried using

let text = document.previousSibling.value;
. As someone new to coding, I feel a bit lost and would appreciate any assistance!

let postArr = document.querySelectorAll('#post');
let inputBox = document.querySelectorAll('#commentBox').values;

function updateComments(){
   postArr.forEach(function(btn){
       btn.addEventListener("click", function(){
           let li = document.createElement("li");
           let text = document.createTextNode(inputBox[i]);
           li.appendChild(text);
           document.getElementById("unordered").appendChild(li);
     
        });
   })

}

Below is the relevant HTML:

<section class="article">
    <h3>BLOG POST #1</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam reiciendis eius veritatis possimus magni esse, ipsum vel consectetur,
        alias tenetur quis. Assumenda saepe aperiam vero cupiditate iusto perspiciatis provident. Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Placeat perspiciatis quis ipsam sunt voluptates suscipit, alias omnis in possimus libero quam quos. Quidem unde eum accusamus eos eligendi, possimus ratione.</p>
        <section class="commentList">
            <ul id="unordered">
           
            </ul>
        </section>
        
        <section class="comment">
            <label>LEAVE A COMMENT</label>
            <input type="text" id="commentBox" placeholder="Enter comment">
            <button id="post" onclick="updateComments()">POST</button>
            <button class="like" onclick="updateLike()">LIKE</button>
        </section>
        <button class="save">SAVE FOR LATER</button>
    </section>

<section class="article">
    <h3>BLOG POST #2</h3>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam reiciendis eius veritatis possimus magni esse, ipsum vel consectetur,
        alias tenetur quis. Assumenda saepe aperiam vero cupiditate iusto perspiciatis provident. Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Placeat perspiciatis quis ipsam sunt voluptates suscipit, alias omnis in possimus libero quam quos. Quidem unde eum accusamus eos eligendi, possimus ratione.</p>
    <section class="commentList">
        <ul id="unordered">
       
        </ul>
    </section>
    <section class="comment">
        <label>LEAVE A COMMENT</label>
        <input type="text" id="commentBox" placeholder="Enter comment">
        <button onclick = "updateComments()" id="post">POST</button>
        <button onclick= "updateLike()" class="like">LIKE</button>
    </section>
    <button class="save">SAVE FOR LATER</button>
</section>

Answer №1

Getting close: when the button is clicked, extract the value and add the comment without the need for additional click listeners or selecting all elements individually. Instead, pass a reference to the button to a function that will handle the action. You can then utilize `previousSibling` since unique IDs or other references are not available.

This method may not be optimal. Consider reorganizing the HTML to incorporate unique IDs and passing them to the function. By doing so, you can replace the use of `previousElementSibling` with `querySelector`.

Here's an example:

    function updateComments(btn) {

        console.log('updateComments, button: ', btn, 'input value: ', btn.previousElementSibling.value, 'list: ', btn.parentElement.previousElementSibling)

        // Access the UL element
        const list = btn.parentElement.previousElementSibling.firstElementChild;

        let li = document.createElement("li");
        let text = document.createTextNode(btn.previousElementSibling.value);
        li.appendChild(text);
        list.appendChild(li);

        // Reset input field
        btn.previousElementSibling.value = '';
    }
<section class="article">
        <h3>BLOG POST #1</h3>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam reiciendis eius veritatis possimus magni esse, ipsum vel consectetur, alias tenetur quis. Assumenda saepe aperiam vero cupiditate iusto perspiciatis provident. Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat perspiciatis quis ipsam sunt voluptates suscipit, alias omnis in possimus libero quam quos. Quidem unde eum accusamus eos eligendi, possimus ratione.</p>
        <section class="commentList">
            <ul id="unordered">
            </ul>
        </section>
        <section class="comment">
            <label>LEAVE A COMMENT</label>
            <input type="text" id="commentBox" placeholder="Enter comment">
            <button id="post" onclick="updateComments(this)">POST</button>
            <button class="like" onclick="updateLike()">LIKE</button>
        </section>
        <button class="save">SAVE FOR LATER</button>
    </section>
    <section class="article">
        <h3>BLOG POST #2</h3>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam reiciendis eius veritatis possimus magni esse, ipsum vel consectetur, alias tenetur quis. Assumenda saepe aperiam vero cupiditate iusto perspiciatis provident. Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat perspiciatis quis ipsam sunt voluptates suscipit, alias omnis in possimus libero quam quos. Quidem unde eum accusamus eos eligendi, possimus ratione.</p>
        <section class="commentList">
            <ul id="unordered">
            </ul>
        </section>
        <section class="comment">
            <label>LEAVE A COMMENT</label>
            <input type="text" id="commentBox" placeholder="Enter comment">
            <button onclick="updateComments(this)" id="post">POST</button>
            <button onclick="updateLike()" class="like">LIKE</button>
        </section>
        <button class="save">SAVE FOR LATER</button>
    </section>

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

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

Multer is not accurately processing the formData

When using Multer to handle Form Data, all fields, including image files, are left in the req.body object. Check out the code snippet below: In React: const state = { // other fields images: [], // array of image files }; let formData = new FormData( ...

Display a div when collapsing in Bootstrap for screen widths of 991px or smaller

I am currently working on optimizing the mobile version of my website using Bootstrap. There is a div element that is taking up too much space on the page, and I would like to hide it on page load for screen widths of 991px or less. I want users to have th ...

Node.JS utilizes non-blocking IO, while frameworks like ASP.NET MVC achieve non-blocking IO through the use of async/await

What sets apart the node.js non-blocking model from the ASP.NET MVC non-blocking async/await with Tasks? Are they effectively addressing the same issue in a similar manner, or am I overlooking something crucial? Could it be possible that other frameworks ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

Encountered a problem while attempting to execute npm run dev on laravel combined with inertia in a

It seems that the issue persists despite multiple attempts to fix it. From clearing cache to reinstalling npm and deleting node-modules and package-lock, nothing has resolved this error so far. Good day! Despite my efforts to troubleshoot by clearing cach ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

Troubleshooting a positioning issue in an ExtJs Grid due to a CSS conflict

After integrating the ExtJs Grid into my existing webpage, I encountered a CSS conflict. The conflicting CSS was identified in my current stylesheet, but unfortunately I am unable to modify it as the entire website is built upon it. Attempts with ctCls, b ...

Encountering an NPM start issue

I encountered an error while trying to execute the "npm start" command on my Windows 10 machine. My npm version is 2.13.3 and I am attempting to run an Express server. 0 info it worked if it ends with ok 1 verbose cli [ 'node', 1 verbose cli & ...

When using jsPlumb's beforeDrop function alongside ngToast, the message may not display immediately

I have been working on a project where I am integrating the jsPlumb library to create a node-based interface. jsPlumb provides an event called 'beforeDrop' which is triggered before connecting two endpoints. I plan to use this event to check a c ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Automating the deployment of a vue.js app using GitLab CI/CD pipeline to deploy to

Currently experiencing an issue with the pipelines involving my YAML file that automates deployment of a Vue app to Firebase. Despite including scripts in the file and setting up the Environment variable FIREBASE_TOKEN on GitLab, pushing the code to a GitL ...

Angular.js, require.js, and jQuery Plugin all combined to create a uniquely customized directive

As a newcomer to Angular and Require, I am seeking assistance with the following code snippet. Despite successfully integrating Angular and Require, I am facing an issue where the bootstrap-switch element fails to initialize: define(['myapp.ui/module ...

What is the best way to display an element once an input field with type "date" is populated with a value

Struggling to create a dynamic form that reveals additional fields when a date picker is used? I've searched for solutions, but everything I find involves complex validations and logic that exceed my needs. I've had some success with revealing e ...

Enhanced feature in Mongoose for updating nested array elements

My Schema looks like this: UserSchema: Schema = new Schema({ username: String, password: String, chat: [{ lastSeen: { type: Date, default: Date.now }, room: { type: Schema.Types.ObjectId, ref: 'ChatRoom' } }], }); I ...

Shapes and their corresponding encoded representations compiled in a comprehensive catalog

Can anyone provide me with a comprehensive list of HTML escaped codes for displaying various shapes on web pages? I need codes that are universally compatible with all browsers. For instance, I would like to display a square using an escaped code in one ...

Guide on connecting MySQL 'id' to an HTML element

I need assistance with setting up a functionality on my website. I have a database containing rows of data, and each row has an 'ID' field in MySQL. I want to connect each ID to a button so that when the button is clicked, a PHP script will run t ...

Steps to incorporate an image overlay onto a clickable button

I'm currently working on enhancing the appearance of my T-Shirt color buttons by adding a heathered image overlay. While some shirts have plain colors, I want to show a pattern overlay on others. How can I include an image for specific buttons that ar ...

Searching for Node/MongoDB matches

Currently, I am managing 3 different Schemas: UserFavorite Schema: This schema is designed to store the favorites selected by the user. var UserFavoriteSchema = new Schema({ _id: { type: Schema.ObjectId, auto: true }, favorite ...