Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery.

You can check out my demonstration page on Codepen for reference.

In the demo, you'll notice a blue submit button. When you input text into the field, the button becomes active.

I'd like to implement a feature where the button turns red when disabled and blue when enabled.

I've created CSS styles for .enableOnInput and .red.

.enableOnInput {
  /* CSS properties */
}
.red {
  /* CSS properties */
}

Below is the jQuery code for enabling/disabling the button:

$(function(){
     $('#searchInput, #searchInput2').keyup(function(){
          if ($(this).val() == '') { 
               // Disable the button if no text is entered
               $('.enableOnInput').attr('disabled', 'true');
               $(".aa").show();
               $(".bb").hide();
          } else {
               // Enable the button if there is text
               $('.enableOnInput').attr('disabled', false);
               $(".aa").hide();
               $(".bb").show();
          }
     });
});

Answer №1

Include the following CSS declaration:

input:disabled
{
  background-color: blue;
  /*additional style attributes*/
}

Answer №2

To easily toggle classes, you can utilize the addClass/removeClass methods.

 $('#searchInput, #searchInput2').keyup(function(){
      if ($(this).val() == '') { //Verify if there is text entered
           //If no text in input, disable button and add 'red' class
           $('.enableOnInput').prop('disabled', true).addClass('red');
           $(".aa").show();
           $(".bb").hide();
      } else {
           //Enable button if text present, remove 'red' class
           $('.enableOnInput').prop('disabled', false).removeClass('red');
           $(".aa").hide();
           $(".bb").show();
      }
 }).keyup();

I've also included a trigger for the keyup event to check initial state and apply the correct class.

Update: Another suggestion from @Terry in the comments is to change the CSS selector from .red to .enableOnInput:disabled, using just

$('.enableOnInput').prop('disabled', true)
. Keep in mind that this won't work on IE8 and earlier versions.

See it in action here: http://codepen.io/anon/pen/CELut?editors=001

Answer №3

Add a touch of elegance by adding the red class to your button

<input type='submit' name='submit' id='submitBtn' class='enableOnInput red' disabled='disabled' />

Enhance the style with this CSS rule:

.red{
  background-color:red;
}

Update your JavaScript code as follows:

$(function(){
     $('#searchInput, #searchInput2').keyup(function(){
          if ($(this).val() == '') { //Check for empty input
               //Disable the button when no text is entered
               $('.enableOnInput').attr('disabled', 'true');
               $(".aa").show();
               $(".bb").hide();
            $('#submitBtn').addClass('red');
          } else {
               //Enable the button when there is text in the input
               $('.enableOnInput').attr('disabled', false);
               $(".aa").hide();
               $(".bb").show();
            $('#submitBtn').removeClass('red');
          }
     });
});

For more inspiration, visit the Updated Link

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

Change the appearance of the page when it is being displayed within an iframe using CSS

How can I display a webpage differently using CSS if it is within an iframe? I would like to use jQuery or JavaScript to switch to a different stylesheet specifically when the site is being displayed within an iframe. Any suggestions on how to achieve th ...

Load the React chunk CSS dynamically to optimize performance and only when it is necessary

After running an audit, Lighthouse is advising me to "Defer unused CSS" for my React app. Despite implementing code splitting and having separate CSS files for each chunk, the suggestion persists. One particular example highlighted by Lighthouse is the foo ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

Combining two flex elements with auto-growing capabilities in react-native

I am excited about using react-native to have a TextInput aligned with a MaterialIcons.Button in the same line. I have been trying to center these elements horizontally but haven't been successful with the code below: import React from 'react&apo ...

Establishing the Time-to-Live (TTL) with Redis-OM and Node Object Mapping

Recently, I stumbled upon the exciting new Redis-OM Node Object Mapping feature. Although I have limited experience with Redis, I am eager to dive into it now. Currently, I have a basic function in place for creating rooms but I want these rooms to automa ...

Trouble with z-index property within the confines of the <ion-segment-button></ion-segment-button> tag

The z-index property seems to be having no effect on the elements within the ion-segment-button. I attempted to adjust the positions of the elements and set the z-index to 999999 with the button z-index set to -1. However, this solution did not work as ex ...

"Using JavaScript to find and manipulate objects within an array by either removing them or adding

I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach: // Object in ...

Performing a jQuery ajax request on data that has been dynamically loaded using

I am currently in the process of constructing a form for users to make reservations on a website. I have successfully set it up so that when a user selects a shift, the available dates are populated. Now, my goal is to have the available seats load when a ...

Loop through the data string in Ajax using a For Loop to populate it

I am currently working on a loop that inserts select tags based on the number of rows. Each select tag will have an ID like selID0, selID1, selID2, and so on. My goal is to call an AJAX function to determine which tag is not selected when the submit button ...

<div.content> </div.content> - Structure

I recall encountering this code before but I can't remember where: <div.main> // .... </div.main> <div.secondary> // .... </div.secondary> Could someone please clarify for me what this syntax is referred to as and what ...

What steps can be taken to ensure the CSS/HTML image aspect ratio remains consistent on various monitors?

My square-shaped image (1:1 aspect ratio) is displaying differently across various devices when I use the codes below. While some show it as a perfect square, others display it as a rectangle. Is there a solution to maintain the original aspect ratio consi ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Error message "SyntaxError: Unexpected token < in JSON at position 0" encountered while using AJAX

When data is sent through an ajax request and processed, a returned array is encoded into json format. $response = array( 'data' => $leaveData, 'message' => 'Event added successfully', ...

Tips for perfectly centering a light box and concealing a scrollbar

Hello, I'm a web designer and facing an issue with the alignment of my lightbox. The lightbox is not center aligned on any resolution, which is causing some trouble. I have also added a black overlay for transparency in the background, but it's s ...

How can I create a unique visual effect on the background in frontend development using chipped design techniques?

Creating a static website utilizing React. Description I am looking to incorporate a visual effect into the website pages, similar to the one demonstrated below. visual effect The goal is to design a rectangular background with triangles cut out from it ...

Running Javascript code after rendering a HandleBars template in Node/Express

I have a Node.js application where I am trying to load data into a jQuery datatable after the data has been fetched. Currently, I am able to populate the table with the data, but I am facing issues initializing the datatable. Here is how I render the temp ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

Top Strategies for PHP - Managing Directs and Header Content

PHP is a versatile language frequently used for generating 'templates' like headers to maintain a consistent look across websites and simplify updates via require or include commands. Another common task involves managing log-ins and redirecting ...

Sending multiple data from a View to an Action method

Below is a snippet of code that has prompted me to ask three questions: JScript in the view: $('#page1').load('@Url.Action("QuestionList", "Tests", new { testId = Model.Test.ID , Page = 2 })'); Action in the Tests controller: publi ...