Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the selected button.

<div class="input-group">
      <input type="text" id="display" class="form-control" aria-label="Text input with dropdown button" >
      <div class="input-group-btn">
      
    
        <div class="dropdown-menu dropdown-menu-right">
          <button type="button" class="dropdown-item" value="1000">1000</button>
          
          <button type="button" class="dropdown-item" value="2000">2000</button>
          <div role="separator" class="dropdown-divider"></div>
          <button type="button" class="dropdown-item" value="3000">3000</button>
          <div role="separator" class="dropdown-divider"></div>
          <button type="button" class="dropdown-item" option value="4000">4000</button>
        
        </div>
      </div>
    </div>
  </div><br><br>
<input name="submit" type ="submit" value="click to submit">
<input name="reset" type ="reset" value="Reset">
</fieldset>
</form>

<script type="text/javascript">
var buttons = document.querySelectorAll('.dropdown-item')
var textbox = document.getElementById('display')

for (let i=0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function(e) {
        textbox.value = e.target.value
    })
}
</script>

Answer №1

You can create a CSS class to highlight the active button by utilizing the this keyword in the event listener. To remove the class from all buttons, you can manipulate the buttons collection.

If you encapsulate this functionality into a separate function, you can easily trigger it on the form's reset event.

Here is an example implementation:

let form = document.querySelector('#yourForm');
let buttons = document.querySelectorAll('.dropdown-item');
let textbox = document.getElementById('display');

let setAllButtonsInactive = () => buttons.forEach(btn => btn.classList.remove('active'));

buttons.forEach(btn => {
  btn.addEventListener("click", function(e) {
    textbox.value = e.target.value;
    setAllButtonsInactive();
    this.classList.add('active');
  })
});

form.addEventListener('reset', setAllButtonsInactive);
button.active { 
  background-color: #C00;
  color: #FFF;
}
<form id="yourForm">
  <fieldset>
    <div>
      <div>
        <div class="input-group">
          <input type="text" id="display" class="form-control" aria-label="Text input with dropdown button">
          <div class="input-group-btn">
            <div class="dropdown-menu dropdown-menu-right">
              <button type="button" class="dropdown-item" value="1000">1000</button>
              <button type="button" class="dropdown-item" value="2000">2000</button>
              <div role="separator" class="dropdown-divider"></div>
              <button type="button" class="dropdown-item" value="3000">3000</button>
              <div role="separator" class="dropdown-divider"></div>
              <button type="button" class="dropdown-item" option value="4000">4000</button>
            </div>
          </div>
        </div>
      </div>
    </div><br><br>
    <input name="submit" type="submit" value="click to submit">
    <input name="reset" type="reset" value="Reset">
  </fieldset>
</form>

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

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

What is the most effective method for creating posts, pages, and their corresponding URLs using Next.js and MongoDB

Here's a glimpse of my MongoDB data: { "_id": { "$oid": "630f3c32c1a580642a9ff4a0" }, "title": "this is a title", "paragraph": "this is a paragraph" } Now, let's t ...

The draggable() function in jQuery and the ng-repeat directive in Angular make for a powerful combination

The code snippet I have is as follows. HTML <div ng-repeat="item in canvasElements" id="declareContainer"> {{item}} </div> Javascript (Angular) (function(){ //angular module var dataElements = angular.module('dataElements' ...

Efficient React search feature with pagination that avoids redundant setState calls

Currently in the process of incorporating search functionality with pagination in React. After reviewing numerous examples, it appears they all involve using setState() twice, both before and after making an AJAX call to the backend. Here is a snippet of m ...

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Struggling to make npm and sqlite3 function properly on MacOS Catalina

Struggling with npm package installation in a project directory on my Mac has proven to be quite the challenge. Each attempt at a simple npm install results in perplexing errors that I can't seem to grasp. The hurdle seems to center around specific p ...

Troubleshooting Node.js TypeScript breakpoints in Visual Studio Code

I've attempted multiple solutions, but none seem to be working for me. Although the code is running, I'm having trouble setting breakpoints and debugging it. Can you offer any assistance? Below is the configuration script I've tried in VSCo ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

Switching between table rows - managing open rows efficiently

Currently, I am working on an extensive database project involving pulling a large amount of data from a database. My focus is on displaying basic information in one visible row while concealing more detailed information in another row. By clicking the &ap ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

Enhancing Django's login form validation with AJAX

I'm trying to implement an AJAX login feature in Django. The goal is to check if the user has provided the correct username and password. Take a look at my current code setup: urls.py urlpatterns = [ url(r'^$', views.home_view, name=&a ...

Change Node.js version to 6.11.5 on a Windows system

My current node version is v8.2.1, but Google Cloud Functions only supports v6.11.5. I need to switch my node version accordingly and preferably do it using npm. How can I achieve this? I have explored How to change to an older version of node.js for guid ...

What is the process for adjusting the expiration time of a GitLab accessToken?

I am currently using NextAuth for logging in with GitLab, but I am encountering an issue where my accessToken changes every 2 hours. How can I ensure that it remains valid for a longer period so that I can successfully store it in my database? It's wo ...

Ways to prevent adding duplicate elements to a state array in React.js?

The state provided below is within my class component. I need to prevent adding duplicate objects to an array in my state as shown below: this.state = { frequency: { time: [ {time:"20:15",timezone:"IST"}, ...

Utilizing jQuery taggd to add annotations to images

I am currently utilizing the taggd Plugin to develop an application that creates a tag whenever any part of the body is clicked. I have successfully implemented most aspects of it, but I am facing an issue with the coordinates. The tags are sometimes creat ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...