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

Eliminating Non-Breaking Spaces with the Click of a Button

Having some difficulty with the following Javascript code. I'm not very skilled in writing Javascript, so any assistance on adjusting it to replace any &nbsp; with a regular space would be greatly appreciated. Thank you function copyToClipboard( ...

What is the best way to retrieve the [id]/routeName in Next.js?

I'm working on a straightforward project where users visit links like: localhost:3000/course/[id]. Once they click join, the URL will transform to localhost:3000/course/[id]/routeName. How can I organize folders like that within pages? Thank you in ad ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button. function addNewItem() { //ADD ROW AND CLONE var table = document.getElementById('tbl'); var tbody = document.create ...

How to dynamically modify a list box with JavaScript

I have an index.html file with a select tag containing multiple options for a drop-down: <label for="edu">Education</label> <select id="edu" name="edu"> <option value="0">10th</option&g ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

The MAC slideshow circles at the bottom have been mysteriously chopped off

Utilizing the popular JQuery plugin Cycle for a slideshow on this site: bybyweb.com/pbm An issue has arisen - everything functions as expected on windows (across all major browsers), BUT on MAC (running lion 10.7.5, tested on one machine so far; unsure of ...

Responsive Bootstrap tables nested within responsive tabs

Utilizing footable in conjunction with Boostrap Responsive Tabs leads to an issue post-resize. When the page is initially loaded on a desktop, everything functions properly until the screen is resized. Once the screen is resized, the tables within the tabs ...

I am experiencing issues with staying logged in while using Passport and sessions. The function "isAuthenticated()" from Passport continuously returns false, causing me to not remain logged in

I have been working on implementing authentication with Angular, Passport, and sessions. I can successfully create a new user and log in, but I am facing an issue: Problem Every time I check if the user is authenticated using Passport's isAuthentica ...

Make sure to validate for null values when extracting data using the useSelector hook

Could someone help me with checking for null while destructuring data? const { vehicles: { data: { reminderVehicles }, }, } = useSelector((state) => state); The code snippet above is throwing an error message: Attempting to ...

Ways to streamline a form containing several duplicate rows and make it more user-friendly

Looking for some advice on implementing a "working hours" module. Just need something simple like: Monday: 10:00 - 18:00 ... Saturday: 11:00-16:00 with some additional info. I'm currently attempting to... <form id="working_hours"> <s ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

The filter functionality is not functioning properly in AngularJS

Currently, I am working on an AngularJS extension and encountering an issue with the filter functionality. In the popup page of my extension, there is a button. Upon clicking this button, the ancestor node of the button gets blocked, and its relevant info ...

How to ensure scrollbar adjusts to increasing height when using scroll:auto?

My <div> element has the style property scroll:auto. Whenever text is added to the <div> and the content height exceeds the default height, I find myself having to scroll down in order to see the latest lines of text that have been added. What ...

Check the row in a JQuery table by using the .on("click") function to determine if a hyperlink within the row was clicked or if

I am in the process of building a website using the following libraries: Parse.js: 1.4.2 JQuery: 1.11.2 and 1.10.3 (U.I.) Twitter Bootstrap: 3.3.4 To demonstrate what I am trying to achieve, I have set up this JSfiddle with placeholder data: https://jsf ...

What is the importance of utilizing clearInterval to restart the timer in ReactJS?

Consider the code snippet provided below: useEffect(() => { const interval = setInterval(() => { setSeconds(seconds => seconds + 1); }, 1000); return () => clearInterval(interval); }, []); What is the purpose of returning ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

How to vertically align an image within a div that has a variable height

Is there a way to center an image vertically within a div that is 1/5 of the screen's height? I have managed to horizontally center the image, but vertical alignment seems tricky. Here's the code I've tried so far: http://jsfiddle.net/ws911 ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...