Instructions for connecting a button and an input field

How can I connect a button to an input field? My goal is to make it so that when the button is clicked, the content of the text field is added to an array (displayed below)

const userTags = [];
function addTags(event) {
   userTags.push(event.target.__ what should I use here to retrieve the input data? __)
}

<label>
   Tags: <input type="text" name="todoTags"/> <button>Create new tag</button>
</label>

Once more, I am attempting to establish a connection between the button and the input field so that clicking the button will capture the input field data and append it to the 'userTag' array using the addTags() function.

Answer №1

To access the label in your callback function, utilize the event target by using

const parent = e.target.closest('label')
. Then, employ querySelector() to retrieve the input element nested under this label tag with
const input = parent.querySelector('input')
. Next, store the input's value in a variable like const inputValue = input.value, and proceed to add this value to your array.

Your callback function should be placed within an event listener for click events.

const btn = document.querySelector('.btn')
const userTags = []

function getValue(e) {
  const parent = e.target.closest('label')
  const input = parent.querySelector('input')
  const inputValue = input.value
  if (inputValue !== "") {
    userTags.push(inputValue)
  }
  console.log(userTags)
}

btn.addEventListener('click', getValue)
<label>
   Tags: <input type="text" name="todoTags"/> <button class="btn">Create new tag</button>
</label>

Answer №2

let valueArray = []
function storeValue(){
let data = document.getElementById("input").value
valueArray.push(data)
document.getElementById("Output").innerHTML = valueArray
}
<body>
<input type="text" id="input">
<button onclick="storeValue()">Save</button>
<div id="Output"></div>
</body>

Access the element using document.getElementById and retrieve its value

document.getElementById("Enter ID Here").value

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

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

Struggling to create responsive embedded videos?

I have successfully created a responsive video, but there seems to be an issue with the width to height ratio when the browser is fully stretched. The iframe appears narrow and tall in this situation. However, when the browser is resized and the video move ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

"Obtaining Data from Local Storage on a Different Page: A Step-by-

``How can I transfer JSON data stored in local storage from one page to another within the same domain? In MainPage.html, the "user" data is stored in local storage and displayed. However, when data is added in AddEmploye.html and then returning to MainPa ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

Show the form for user input

I have an HTML code for a form that requires input. Once the 'OK' button is clicked, the values are sent to a PHP script using $_POST. Is it possible to display the same form again if the input format is incorrect, but do so only within my PHP sc ...

How does the single-threaded nature of Node.js handle an abundance of concurrent requests?

I'm currently delving into the world of nodejs, trying to wrap my head around its single-threaded nature. Here's a pondering I have: Let's say I implement a non-blocking method and we have 20000 concurrent requests flowing in. If one request ...

Error: The function nodemailer.createTransport is not defined or does not exist

I'm currently working on integrating nodemailer into my nodejs application for sending emails. Check out the code below: var express = require('express'); var nodemailer = require('node-mailer'); var app = express(); app.post(&a ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...

Using brackets in a CSS background-image URL will cause it to malfunction and not display the

Try using the brackets editor tool available here. I attempted to add an image to a div with the class "portrait" by linking the style.css file from index.html, but it doesn't seem to be working. Other guides and tutorials have successfully utilized ...

Using Handlebars.js to conditionally display data within an object is not functioning as expected

I am attempting to retrieve JSON data value and only display the element if the data is present. However, I am experiencing issues with Handlebar JS. var data = { listBank: [ { "enableSavedCards":"false", "enableAxisAccount":"t ...

Creating a JavaScript function to automatically hide a dropdown menu after a specific duration

I'm currently working on a side menu that drops down when hovering over Section One within the <a> tag. I need some guidance on how to make the JavaScript code continuously check the state of the list after a set amount of time in order to autom ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

Identify the activation of the "Inspect Element" feature

On Samy Kamkar's personal website at , there is a clever feature that detects when the console is opened and automatically clears the source code/console. It's a fascinating display of coding magic! https://i.stack.imgur.com/kag6U.jpg Curious t ...

Utilizing the active tab feature within CSS

I am currently working with a detailed structure of bootstrap theme classes. Currently, I am in the process of designing a menu. This is the code snippet for the navigation bar design in Bootstrap- <div class="navbar navbar-fixed-top navbar-invers ...

Steps to animate a div expanding to fit its content dimensions

I'm looking for a way to animate the opening of a div so that it adjusts to the size of its content. The content is fetched from a separate search using .load, which means it could be just a single line (no result) or multiple results that vary in hei ...