Is there a way to change the color of the icon when the input fields are filled?

I am trying to change the color of the related icon for inputs when they are focused on or not empty, but my code doesn't seem to be working correctly for non-empty inputs.

                    <div class="form-group">
                        <label class="label-login" for="emailInput">Email</label>
                        <input type="email" class="form-control" autocomplete="off" id="emailInput" />
                        <i class="fa fa-envelope"></i>
                    </div>
                    <div class="form-group">
                        <label class="label-login" for="passInput">Password</label>
                        <input type="password" class="form-control" autocomplete="off" id="passInput" />
                        <i class="fa fa-lock"></i>

                    </div>

   $(document).ready(function () {
     $(".myPanel .form-control").each(function () {
    var valueInput = $(this);
    valueInput.focus(function () {
        valueInput.next().addClass("colorOrange");    
    });

    valueInput.blur(function () {
        valueInput.next().removeClass("colorOrange");
    });
    valueInput.on('input', function () {
        if (valueInput.val().length > 0) {
            valueInput.prev().addClass("lableFocus");
            valueInput.next().addClass("colorOrange");
        } else {
            valueInput.prev().removeClass("lableFocus");
            valueInput.next().removeClass("colorOrange");
        }
    });
   });
});
  .colorOrange{
       color:#FFAE00;
  }

Answer №1

I've found a solution to reduce the length of the code slightly. I hope this simplifies things for you.

$( ".form-control" ).focusin(function() {
  $( this ).next( "i" ).css( "color", "#FFAE00" );
});
$( ".form-control" ).focusout(function() {
  $(this).val().length === 0 ? fontColor = "#000" : fontColor = "#FFAE00";
  $(this).next( "i" ).css( "color", fontColor );
});
.colorOrange {
  color: #FFAE00;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="form-group">
  <label class="label-login" for="emailInput">Email</label>
  <input type="email" class="form-control" autocomplete="off" id="emailInput" />
  <i class="fa fa-envelope"></i>
</div>
<div class="form-group">
  <label class="label-login" for="passInput">Password</label>
  <input type="password" class="form-control" autocomplete="off" id="passInput" />
  <i class="fa fa-lock"></i>
</div>

Answer №2

To achieve this effect using only CSS, you can utilize the :valid pseudo class. This will enable you to style elements based on their validity status.

/* HTML */

    <div class="form-group">
       <label class="label-login" required for="passInput">Password</label>
       <input type="password" class="form-control" autocomplete="off" id="passInput" />
       <i class="fa fa-lock"></i>
    </div>

/* CSS */
input:valid + i.fa-lock {
   color: $your-valid-color;
}

Here are some important points to keep in mind:

  • Make sure to set the input as required for the :valid class to take effect.
  • An non-empty type="text" element will also be considered valid.
  • You have the option to define a regex pattern or use the minlength attribute to impose constraints on what is counted as valid.

For more detailed information, refer to the complete documentation here. The basic html form and input fields offer extensive functionality, allowing you to accomplish many tasks with just these elements.

Answer №3

The problem lies in the scope of your code. The variable valueInput is defined within the .ready() function, so it is not accessible within the .blur() and .on() functions. Instead, you should use this in those functions, as it refers to the element that initiated the event.

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

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

Enhancing list item appearance by replacing bullets with Font Awesome icons

I need to create a list similar to this example https://i.sstatic.net/w84xS.png Although I successfully replaced the bullet with a fontawesome icon, the result is not quite right as shown here https://i.sstatic.net/yqnbJ.png You may notice a difference ...

Creating a many-to-many relationship in Sequelize using a join table to insert data

I recently set up two models in sequelize with a many-to-many relationship. While Sequelize successfully created the join table, I am facing difficulties when trying to insert data into it. Despite going through the documentation section on associations ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Access Silverlight to open Windows Explorer

Is it possible to launch Windows Explorer to a specific folder from a Silverlight application running in a browser? Also, is there a method to retrieve the machine name within a Silverlight app? ...

Merge two arrays of objects containing Google Map coordinates

I am facing a challenge with merging two object arrays that have similar values. var Cars = [{ lat: 42, lng: -72 }, { lat: 40.7127837, lng: -74.0059413 }, { lat: 40.735657, lng: -74.1723667 }]; var Trucks = [{ lat: 43, lng ...

How can I use jQuery to display a div alongside the element that is currently being hovered over?

Imagine having multiple divs similar to these: UPDATE: <div class="ProfilePic"> <a href="#"> <img src="lib/css/img/profile_pic1.png" alt="" class="ProfilePicImg"/> </a> <div class="PopupBox" style="display: ...

Working with Vue.js: Binding to dynamically generated form elements

I am facing an issue where form elements are not available in the html document until an inline script runs on page load. In Vue.js, how can I bind to these form elements after the page loads? While with jQuery I could use a $('.element').each(), ...

Top method for achieving a smooth transition in a loading CSS3 animation

Having trouble implementing a fade in/fade out effect on a div with a CSS3 based login animation when a function is loaded. I have set up a jsfiddle but still can't get it to work. Any assistance would be greatly appreciated! http://jsfiddle.net/adam ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Using Bootstrap to center elements only on specific ones

I am currently working on creating a "navbar/toolbar" with one item positioned on the left side (h3) and three items aligned on the right side (a, a, and select). However, I am facing an issue where only the first item (h3) is vertically centered. Can some ...

What steps can I take to ensure a JavaScript loading image is displayed until the entire page has finished loading?

Looking to implement a JavaScript loading image that displays until the page has fully loaded? I'm currently developing an online antivirus scanner and in need of help. I am trying to set up JavaScript to show a loading image while a file is being up ...

Clicking multiple times will impede the progress of AJAX requests

My webpage has multiple buttons that can be clicked very quickly, but it seems like Chrome is struggling to keep up with the speed? $(document).ready(function() { $('.favorite-button').unbind('click').click(function() { addLine ...

How can I fix my HTML Image input not redirecting when clicked?

I have successfully implemented the following code: <input type="button" name="btnHello" value="Hello" onclick="Test();"/> Here is the JS function that accompanies it: function Test() { window.location.href = "Page2.aspx"; } Initially, clicking ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

Using CSS3 to layer two background images on the body element

Looking to create a unique design, I decided to use two images as a fixed background in CSS. Here is the code snippet I used: background: url(images/31.jpg) 100% no-repeat, url(images/12.jpg) 100% no-repeat; background-position: fixed; My goal is to make ...

Leveraging Object.keys() to access search parameters

Given the following code snippet: const [searchParams, setSearchParams] = useSearchParams(); console.log(searchParams.toString()); console.log(typeof searchParams); console.log(Object.values(searchParams)); When a URL like http://localhost:3000/c ...

When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects." In the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...

Using the flexslider to override CSS styles in an <li> element

I have implemented the flexslider by whoothemes on my responsive website to showcase tiles. However, I am facing an issue with setting a specific width for the tiles on various devices. Upon inspecting with Chrome, I see this code: <li style="width: 21 ...