What is the code to create a form that changes the background color of a button when a user begins typing in an input field using JavaScript, HTML, and CSS?

const buttonOne = document.getElementById("btn1");
const inputfieldOne = document.getElementById("username1");

inputfieldOne.addEventListener("keyup", function(e) {
  const valueOne = e.target.value;
  if (valueOne === "") {
    buttonOne.disabled = true;
    buttonOne.style.backgroundColor = "grey";
  } else {
    buttonOne.disabled = false;
    buttonOne.style.backgroundColor = "orange";
  }
})
<div class="container">
  <input id="username1" placeholder="Username" class="input" />
  <button disabled id="btn1" type="button" class="button">Submit</button>
</div>

Currently, this code only works for one specific input and button pair. How can I modify the JavaScript to apply to multiple pairs of input fields and buttons?

I would appreciate any assistance in solving this issue. Thank you.

If you have a complete jQuery solution, that is also welcome.

Answer №1

In my solution, I utilized a custom class to encapsulate both the input and button elements within a div container. By iterating over each of these divs, I was able to access the child inputs and buttons and apply the necessary functionality using the provided code snippet.

const buttons = document.getElementsByClassName('inputButton');

for (let j = 0; j < buttons.length; j++) {
  let inputEle = buttons[j].querySelector('input');
  let btn = buttons[j].querySelector('button');

  inputEle.addEventListener("keyup", function(event) {
    const value = event.target.value;
    if (value === "") {
      btn.disabled = true;
      btn.style.backgroundColor = "grey";
    } else {
      btn.disabled = false;
      btn.style.backgroundColor = "orange";
    }
  });
}
<div class="wrapper">
  <div class="inputButton">
    <input id="user1" placeholder="Username" class="input" />
    <button disabled id="btn1" type="button" class="button">Submit</button>
  </div>
  <div class="inputButton">
    <input id="user2" placeholder="Username" class="input" />
    <button disabled id="btn2" type="button" class="button">Submit</button>
  </div>
  <div class="inputButton">
    <input id="user3" placeholder="Username" class="input" />
    <button disabled id="btn3" type="button" class="button">Submit</button>
  </div>
</div>

Answer №2

To enhance the functionality, you can enclose it within an additional div element and loop through each "input-group". By adding an event listener to the input child within each group, you can easily modify the styling of the button child.

document.querySelectorAll('.input-group').forEach((group) => {
  let input = group.querySelector('input');
  let button = group.querySelector('button');
  input.addEventListener('keyup', () => {
    if(input.value !== "") {
      button.disabled = false; 
    } else {
      button.disabled = true;
    }
  });
});
#btn[disabled] {
  background: red;
}

#btn {
  background: green;
}
<div class="container">
  <div class="input-group">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
  <div class="input-group">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
  <div class="input-group">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
</div>

Answer №3

To efficiently add an event listener to multiple input elements, you can create a loop with a class and use data attributes to connect the button to the respective input field. Additionally, ensure to define your styling in CSS for consistency.

let inputs = document.getElementsByClassName("an-input");
for (let i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener("keyup", function(e) {
    let btn  = document.querySelectorAll("[data-placeholder="+this.placeholder+"]")[0];
    if (this.value === "") {
      btn.disabled = true;
    } else {
      btn.disabled = false;
    }
 })
}
button{
  background-color:orange;
}
button:disabled,
button[disabled]{
  background-color:grey;
}
<input class="an-input" placeholder="Username" class="input" />
<button disabled data-placeholder="Username" type="button" class="button">Submit</button>

<input class="an-input" placeholder="email" class="input" />
<button disabled data-placeholder="email" type="button" class="button">Submit</button>

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

You cannot embed a YouTube video using its iframe code in an HTML document, according to YouTube's guidelines

I attempted to include a YouTube video in my HTML code, but it kept showing the message "YouTube won't allow connection." Here is the code I used: <center><iframe src="https://www.youtube.com/embed/fcPOsBCwyu8" frameborder="0&q ...

Fonts appear altered on a Windows computer

Working on my new website watr.io, I've noticed that the font appears differently on Windows versus Mac. The one displayed on Mac is the desired outcome, but I can't seem to figure out what's causing the discrepancy. I've been troublesh ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

How can you transform an array of objects into an array of strings?

I have an array of objects structured like this- var people = [ {name: 'John', age: 30, address:'123 Main St'}, {name: 'Sarah', age: 25}, {name: 'Mike', age:29, adddress:'456 Elm S ...

Enhance the worth of text box

Is there a way to adjust the value of a textbox by one on keyup, keydown, or tap events? Check out this example. Here is the HTML structure: <div class="right-content" id="rc-0" style="height: 250px;"> <div class="right-cont-main" id="rcm-0" s ...

Why does this function properly on every browser except for Opera?

I have implemented a script that allows me to replace the standard file upload input with a custom image. The script also ensures that an invisible 'browse' button appears underneath the mouse pointer whenever it hovers over the custom image. Thi ...

Tips for creating (icon + label) combinations on the initial page of a jQuery mobile application

Is it possible to create a main menu in a jQuery mobile app's first page with icons and labels underneath each icon? <a href="#sport" id="btn1"> <img src="images/sports.png" ; float: center"/> </a><br /> sports ...

Problems encountered with the ajax contact form embedded in a WordPress theme

I have encountered an issue with a website I am trying to troubleshoot. The form on this particular page: appears to be malfunctioning... The form is failing validation and not sending any emails. The expected functionality is for the form to validate fi ...

Updating documents in a mongoDB collection can be done by simply

I require an update to my database that will modify existing data, as illustrated below: existing data => [{_id:"abnc214124",name:"mustafa",age:12,etc...}, {_id:"abnc21412432",name:"mustafa1",age:32,etc...}, {_id ...

Modifying the column layout of a CSS grid using a media query

I am working on creating a responsive grid layout with a specific breakpoint that should reduce the number of columns to 14. Here is the code snippet I have in my Sass file: #app { --mid-col-size: 60px; --mid-col-amount: 12; --edge-col: 150px; --co ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Node's 'fs' module not triggering the If/Else If block

When attempting to run my CLI application using yargs to parse optstrings, I encountered this error with a lengthy stack trace: (video recording due to its size) I'm unsure of where I've gone wrong. This is the TypeScript code I'm using: i ...

Eliminate items from one BS4 ResultSet that are also found in a different BS4 ResultSet

I am currently working on a web scraping project to extract news articles. I am facing an issue where I need to remove elements with a specific nested class. Here is my code snippet: import requests from bs4 import BeautifulSoup url = 'https://www.mo ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows: <div class="row"> <div class="col-md-12"> <div id="calendar"></div> <table id="report" class="table"> <thead> <tr> <th> ...

What is the best way to determine the width of the browser in JavaScript?

I'm attempting to create a JavaScript function that retrieves the current browser width. After searching, I came across this method: console.log(document.body.offsetWidth); However, it doesn't work well if the body width is set to 100%. Are ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

Sleek and Speedy jQuery Popup Dialog

Seeking a swift and efficient jQuery modal window - wanting something lightweight opposed to the larger jQuery UI modal. Any suggestions for a light-weight jQuery Modal window that offers good speed and performance with ajax capabilities? ...

Utilizing the "return" keyword in Javascript outside of function declarations

Exploring the Impact of Using the Return Keyword in JavaScript Scripts Beyond Functions in Browsers and Node.js Recently, I experimented with utilizing the return keyword in a Node.js script like so: #!/usr/bin/env node return 10; My initial assumption ...

Using an SVG image to change the cursor to a pointer in CSS

I've been attempting to use a custom cursor pointer with an SVG image, but unfortunately, it's not functioning as expected. Interestingly, when I switch to a PNG image, everything works perfectly fine. Below is the code snippet I'm using: ...