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

In order to manage this specific file type, you may require a suitable loader. React in conjunction with Material UI could be the

I recently created a project using Material UI and React JS, but I encountered a puzzling error without making any changes to my app. Despite reaching out for help by creating an issue on MUI, I received no response. The app was generated using npx-create ...

Ways to eliminate the existing image during an image upload process

When a user decides to change their profile picture, I want the link in the database to be updated and the new image moved to the upload folder. The code should also remove the previous image associated with that specific user from the upload folder. The ...

Populate HTML dropdown menu with data from an external JSON file

I'm attempting to populate a HTML Dropdown menu with information from an external JSON file, which consists of the following { "Destinations": [ { "destinationName": "London", "destinationID": "lon" }, { "dest ...

Selecting items from a list at random using the power of math.random() and math.floor()

When attempting to randomize the popping of elements in a list stored in the baby variable, only baby[1] is being popped. How can I make it pop random elements? <body> <h1 id="1">bebe</h1> <h1 id="2">t ...

Is there a way to retrieve the HTML raw code using backticks for string interpolation in JavaScript?

I am working on a resume builder project where the HTML template file is stored in Firebase storage and retrieved using a URL. The template has been modified to include string interpolation, such as <h1>${name}</h1>. However, when I fetch the d ...

Having trouble with innerHTML.value functionality?

Recently, I've been delving into creating a JavaScript program that fetches Wikipedia search results. Initially, everything seemed to be working fine as I was able to display the searched item using the alert() method. However, for some reason, it now ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

Tips for creating a Vue component that triggers the select dropdown to open when the entire div or wrapper is clicked

I have a custom-designed select dropdown with unique symbols for the select arrow. To achieve this look, I've hidden the default select arrow/triangle and placed our symbol on top as an image file. <div class="select-wrapper"> < ...

Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria: Characters Used Password Strength Length ABC abc 123 #$& WEAK ... 1 x ...

jquery's removeClass method successfully removes the specified class, but the changes made by that class are still present

Being new to web design, JS, and all of this, I would greatly appreciate any suggestions :) Currently, I have these img icons (serviceIcon) positioned 'absolute' with their respective classes (serviceHardware, ...). <div class="servicesBox"&g ...

Tips for inserting SVG images into PDF documents

Is there a way to generate a PDF upon clicking the "generate PDF" button? The PDF should display an image containing highlighted squares corresponding to the user's selections on the webpage. I've been struggling to include the SVG in the PDF as ...

What is the best way to adjust the size of the close button in react-bootstrap for a unique design?

<CancelButton className="exitBtn"/> .exitBtn{ height:40px; width:35px; } I'm trying to adjust the dimensions of the cancel button, but for some reason it's not working. Can someone provide guidance on how to successfully ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Problem encountered when transferring JSON data to PHP for file writing

After spending numerous hours researching potential solutions, I still can't seem to fix the issue at hand. Admittedly, I am fairly new to PHP, so it's possible that I am overlooking a small detail. The problem lies in the fact that I have a form ...

I'm having trouble finding the issue in this straightforward code snippet. Can someone pinpoint the error for

(server-side) const express = require('express'); //setting up app instance const app = express(); //middleware const bodyParser = require('body-parser'); app.use(express.urlencoded({extended: false})); app.use(express.json()); //imple ...

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

Unable to pass props to component data using Vue framework

I'm facing an issue with passing props in my component to the same component's data object. For some reason, I'm only receiving null values. Does anyone have any suggestions on how I should approach this problem? It seems like my Vue compone ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...