What is the method for altering the background color of an input field upon entering text?

As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does.

I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of the input field to #00FF7F when something is typed into the field. If nothing is typed, the background should be transparent.

Javascript Code:


$(document).ready(function () {
    var $input1 = $("#logindata1");
    var $input2 = $("#logindata2");

    function onChangeInput1() {
        $input1.css("background-color", "#00FF7F");
        var value = $.trim($(".form-control").val());

        if (value.length === 0) {
            $input1.css("background-color", "transparent");
        }
    }

    function onChangeInput2() {
        $input2.css("background-color", "#00FF7F");
        var value = $.trim($(".form-control").val());

        if (value.length === 0) {
            $input2.css("#background-color", "transparent");
        }
    }

    $input1.on("keyup", onChangeInput1);
    $input2.on("keyup", onChangeInput2);       
});

CSS:


#loginbox {
    width: 400px;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 25%;
}

.logindata {
    margin-left: auto;
    margin-right: auto;
    margin-top: 20px;
    height: 60px;
    width: 290px;
    transition: 0.25s ease;
}

.form-control {
    margin-left: auto;
    margin-right: auto;
    height: 55px;
    width: 288px;
    border-style: none;
    background-color: transparent;
    text-align: center;
    border: solid 2px #00FF7F;
    transition: 0.25s ease;
    font-size: 25px;
    font-family: "Trebuchet MS";
}

... (additional CSS properties)

Simple HTML:

<!DOCTYPE html>
(HTML code)

To see how the Username and Password fields react differently, try typing into both on the provided jsbin link.

You can view images showing the different reactions by following this link: https://i.sstatic.net/RFHs1.jpg

I believe there might be a more efficient way to streamline my javascript/jQuery code using a single function that each input field calls, rather than having a separate function for each.

Answer №1

For situations where both fields are mandatory, a straightforward CSS-only solution is available.

To ensure that the <input> tags are required, simply add the attribute required, followed by utilizing the pseudo-class :valid.

.form-control:valid {
  background-color: #00FF7F;
}

Here is the code snippet:

#loginbox {
  width: 400px;
  height: 200px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25%;
}
.logindata {
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  height: 60px;
  width: 290px;
  transition: 0.25s ease;
}
.form-control {
  margin-left: auto;
  margin-right: auto;
  height: 55px;
  width: 288px;
  border-style: none;
  background-color: transparent;
  text-align: center;
  border: solid 2px #00FF7F;
  transition: 0.25s ease;
  font-size: 25px;
  font-family: "Trebuchet MS";
}
.form-control:hover {
  box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
  color: #00FF7F;
}
.form-control:valid {
  background-color: #00FF7F;
}
<div id="loginbox">
  <div class="logindata" id="logindata1">
    <input type="text" class="form-control" placeholder="Username" required>
  </div>

  <div class="logindata" id="logindata2">
    <input type="password" class="form-control" placeholder="Password" required>
  </div>
</div>

Answer №2

View the code on jsFiddle: here

Using jQuery:

$(document).ready(function() {
 $('.change-background').on('change', function() {
    var $this = $(this);
    var value = $.trim($this.val());

    // ToggleClass can add or remove class based on condition
    $this.toggleClass('filled-background', value.length !== 0);
  }).change();
});

Rather than using the keyup event, simply listen for the change event to change the background color of inputs with the class change-background.

Html snippet:

<div id="loginbox">
  <div class="logindata" id="logindata1">
    <input type="text" class="change-background form-control" placeholder="Username">
  </div>

  <div class="logindata" id="logindata2">
    <input type="password" class="change-background form-control" placeholder="Password">
  </div>
</div>

Css (background color)

.filled-background {
  background-color: #00FF7F;
}

Additional Note

Consider users who may paste their credentials instead of typing, as it may not trigger the keyup event.

Answer №3

Your code has a function that clears the background color when the length is 0. It uses the following snippet to check the length:

var value = $.trim($(".form-control").val());

The issue lies in the selector $(".form-control") because it selects all elements with the CSS class of .form-control, but there could be more than one element with this class, resulting in always getting the value from the first element found.

To solve this problem, you should modify the code to search for the specific control by its ID, like this:

var value = $.trim($("#logindata1 input").val()); //get user ID
var value = $.trim($("#logindata2 input").val()); //get password

Answer №4

You have a few minor errors, but don't worry. We can easily correct them.

Issue Number One

Other responses have pointed out an important detail: you are attempting to retrieve the value by selecting all elements with the class form-control.

var value = $.trim($(".form-control").val());

To fix this, you can use your previously declared variables $input1 and $input2 for selecting the values like this:

var value = $.trim($input1.val());
var value = $.trim($input2.val());

Second Problem

Alright, the first problem is resolved. Now onto the second issue in your second function where you're trying to set an invalid CSS property:

$input2.css("#background-color", "transparent");

The correct syntax should be:

$input2.css("background-color", "transparent");
(without the #).

Moving On

Great progress so far. The IDs you've assigned as logindata1 and logindata2 belong to your div elements. Therefore, you're mistakenly attempting to retrieve the value of the div rather than the input. You can correct this by appending input to your selector, like this:

var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");

Final Touches

So, everything should come together nicely now:

$(document).ready(function () {
    var $input1 = $("#logindata1 input");
    var $input2 = $("#logindata2 input");

    function onChangeInput1() {

        $input1.css("background-color", "#00007F");
        var value = $.trim($input1.val());

        if (value.length === 0) {
            $input1.css("background-color", "transparent");
        }
    }

    function onChangeInput2() {
        $input2.css("background-color", "#00007F");
        var value = $.trim($input2.val());

        if (value.length === 0) {
            $input2.css("background-color", "transparent");
        }
    }

    $input1.on("keyup", onChangeInput1);
    $input2.on("keyup", onChangeInput2);
});

Answer №5

Your validation method needs adjustment. Instead of checking both inputs every time with your jQuery code, focus on checking the individual inputs separately.

Modify your approach by targeting and validating the specific inputs that you are concerned about.

$(document).ready(function () {
    var $input1 = $("#logindata1");
    var $input2 = $("#logindata2");

    function onChangeInput1() {
        $input1.css("background-color", "#00FF7F");
        var value = $.trim($input1.val());

        if (value.length === 0) {
            $input1.css("background-color", "transparent");
        }
    }

    function onChangeInput2() {
        $input2.css("background-color", "#00FF7F");
        var value = $.trim($input2.val());

        if (value.length === 0) {
            $input2.css("#background-color", "transparent");
        }
    }

    $input1.on("keyup", onChangeInput1);
    $input2.on("keyup", onChangeInput2);       
});

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

When using Node.js, res.render may encounter issues, but res.send typically functions properly

Currently, I am in the process of setting up the environment for a node.js app. Unfortunately, I am encountering an issue where the views/ejs files are not being rendered properly. When I use the following code snippet: app.get("/", function(req, res){ ...

Prevent event propagation when a CSS pseudo-element is active

In my project, there are two elements: .parentElement and .childElement. Both have the :active implemented to appear darker when pressed. The .childElement is nested inside the .parentElement. I am looking for a way to prevent the .parentElement:active fr ...

Does the server transmit HTML page content rather than the information you need?

My React application is connected to a backend built with Node.js. However, when I try to fetch data in my React component, the server sends back an HTML page instead of the expected data, displaying raw HTML on the screen. Backend (server.js): app.route ...

Create a registration form that automatically redirects to the login page in case of authentication errors

I am currently working on an index page that features both a login and sign up functionality, each contained within separate divs being controlled by jQuery. One issue I have encountered is that when there are errors during the registration process, the p ...

Naming a JSON object twice

As a newcomer to node.js, I find myself struggling with understanding the process. Can someone please guide me on where I might be going wrong? This is how I create a new Product exports.postAddProduct = (req, res, next) => { const product = new Produ ...

table rows are styled with hover effects and alternating colors using CSS

Styles for even and odd table rows are set, but hovering over the table rows is not working. Test it out here: http://jsfiddle.net/w7brN/ CSS style : #table_even tr:hover { background-color:#fffbae!important; } /* hover effect */ #table_even tr:nth-ch ...

The autoComplete feature in my ReactJs form is not functioning properly

I have a form in React where I would like to enable auto complete so that when users input the same value again, it will be suggested as an auto complete option. Below is the code snippet: <form className={classes.container} noValidate> <Grid c ...

Is it possible to hide a div using Media Queries until the screen size becomes small enough?

Whenever the screen size shrinks, my navbar sections start getting closer together until they eventually disappear. I've implemented a button for a dropdown menu to replace the navbar links, but I can't seem to make it visible only on screens wit ...

obtain data in JSON format from a Node.js server and display it on an HTML

I am currently working on a feature that involves sending an AJAX request to the server and receiving the output of a MySQL query on the page http://localhost:3000/result.html upon clicking a button. <body> <form action="/setLocation" method=" ...

How to extract the root website URL using JavaScript for redirection purposes

I am facing an issue with redirecting to the Login page from every page on my website after session timeout. I attempted to set the window location to the login page using the following code: var ParentUrl = encodeURIComponent(window.parent.location.href) ...

AngularJS: incorporating various functionalities within a single controller

I have a basic AngularJS controller that I am working on, and I would like it to include two separate functions: var app = angular.module('searchApp', []); app.controller('searchCtrl', function($scope, $http, $log) { //Function 1 ...

The expiration period set in expireAfterSeconds doesn't seem to be functioning as expected in the time-to-live (ttl) configuration. Rows are

Can you please take a look at my code and provide some feedback? The issue I am facing is that the record is getting deleted without specifying the number of seconds. I have tried changing from createIndex to ensureIndex but it's still not working as ...

Tips on aligning a div to the right of a headline

My goal is to have an orange circle image placed to the right of my headline <h2>. However, I am facing an issue where the circle jumps above the headline when I shrink the screen. How can I ensure that it stays on the right side no matter the screen ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

Getting rid of redundant elements in an array using Javascript or AngularJS

Case Study 1 A situation arises where an API I am using returns an array with duplicate values. var originalArray = [{id:1, value:23},{id:1, value:24},{id:1, value:22},{id:2, value:26},{id:3, value:26}]; //example Inquiry 1 -> How can I remove the du ...

Column with a set width in Bootstrap

Is it possible to create a fixed width right column in Bootstrap while keeping the left column responsive? I am currently working with Bootstrap 2.3.2 https://i.stack.imgur.com/xOhQo.png (source: toile-libre.org) I want the right column to maintain it ...

Comparing Angular 5 with --aot and Angular 5 with --aot=false configuration settings

I am having an issue with my Angular application using Angular 5.0.0 and rxjs ^5.5.2. When I run the command ng serve --aot=false, everything works fine. However, when I use ng serve --aot, I encounter the following error: core.js:1350 ERROR Error: Uncaug ...

Despite successful installation, node remains elusive on Ubuntu VPS

After installing node using NVM with version 0.25.0, I specifically installed node version 0.10.32. However, upon running node -v, the following error is displayed: -bash: /root/.nvm/v0.10.32/bin/node: No such file or directory Similarly, when executing ...

How to utilize Bootstrap 5 flex for aligning text in the center position

Within these specific divs: <div class="col-6 col-md-4 col-lg-3 col-xl-2 my-3"> <a href="#" title="Falazóhabarcs" class="main_category d-flex justify-content-between align-items-center radius p-3&quo ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...