Adding a class to an element can be easily achieved when both input fields have values

Is it possible to apply the "active" class to the element go_back_right only when both inputs with classes search_box_name and search_box_id have content in them? I've tried looking for solutions on this platform, but being new to JavaScript, I couldn't find a suitable answer. Any assistance would be greatly appreciated.

.go_back_right:active {
  background-color: rgba(255, 0, 0, 0.05);
  animation: status 4s ease forwards;
}
<div class="search_box_container">
  <input class="search_box_name" id="search_bar username" for="username" name="username" type="text">
  <input class="search_box_id" id="search_bar roomNamehtml" name="room" type="text">
</div>

Answer №1

Here is a jQuery code snippet that demonstrates setting an event for adding or removing a class:

$(document).ready(function () {
    setEvents();
    $('.search_box_container').trigger('change');
});
function setEvents() {
    $('.search_box_container').on('change', function () {
        var $this = $(this),
            search_box_name = $this.find('.search_box_name').val().trim(),
            search_box_id = $this.find('.search_box_id').val().trim();
        if (search_box_name && search_box_id) {
            $('.go_back_right').addClass('active');
        } else {
            $('.go_back_right').removeClass('active');
        }
    });
}

Answer №2

It appears that you are looking to assign an additional class to the element identified by the class .go_back_right. If that is the case, you can include the following in your JS file:

const searchBoxName = document.getElementByClassName('search_box_name');
const searchBoxId = document.getElementByClassName('search_box_id');
const goBackRight = document.getElementByClassName('.go_back_right');

const addClass = () => {
  if (searchBoxName && searchBoxName.value && searchBoxId && searchBoxId.value) {
    goBackRight.classList.add('active');
  }
}

addClass()

For more information, you can refer to this, this, and this. Additionally, please note that having multiple elements with the same id like the search_bar id on both your inputs is not recommended.

Answer №3

function checkInputs() {
  if (document.querySelector(".search_box_name").value !== "" && document.querySelector(".search_box_id").value !== "") {
    document.querySelector(".go_back_right").setActive();
  } else {
    document.querySelector(".go_back_right").setActive(false);
  }
}
checkInputs();
.go_back_right:active {
  background-color: rgba(255, 0, 0, 0.05);
  animation: status 4s ease forwards;
}
<div class="search_box_container">
  <input oninput="checkInputs()" class="search_box_name" id="search_bar username" for="username" name="username" type="text">
  <input oninput="checkInputs()" class="search_box_id" id="search_bar roomNamehtml" name="room" type="text">
</div>

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

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

"Empty array conundrum in Node.js: A query on asynchronous data

I need assistance with making multiple API calls and adding the results to an array before returning it. The issue I am facing is that the result array is empty, likely due to the async nature of the function. Any help or suggestions would be greatly appre ...

Finding the chosen selection in AngularJs

I've been working on this script for hours and I'm struggling to output the text instead of the value of a select option in AngularJS in HTML through data binding. Despite my efforts, I keep getting the value instead of the text. How can I resolv ...

Comparison Between Jquery and Emerging Javascript Frameworks and Libraries such as Angular, Ember, and React

As a ruby on rails developer, my recent foray into learning Angular and React has opened up new possibilities in the world of Javascript technologies. Despite reading comparison posts to gain insight into the reasons behind using different frameworks and l ...

Struggling with identifying jQuery ajax errors?

I am attempting to handle all errors on my own. When an error occurs in jQuery.ajax(), I can detect it using the error options. However, this error is not catchable by my window.onerror event. window.onerror = function(e) { console.log("I was here! E ...

When transferring an object from a blade template to a Vue component through props, it may become undefined

I'm facing an issue where I am attempting to send an array from an asynchronous method in the controller to a Vue component using props within a blade template. However, when I try to log it in the Vue component, it shows up as undefined. Here is the ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

What is the best way to condense all JavaScript and CSS files in MEAN.JS for a production setting?

I recently finished creating a basic MEAN.JS application. When using MEAN.JS, I can use the command grunt build to minify the js and css files located in specific folders: css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config ...

Utilizing $(document).ready Twice: When jQuery Library is Included in Between, Only the Latter Event Executes

I am encountering an issue with the following structure (simplified): // In <head> $(document).ready(function(){ // first event }); // Near the end of <body> // jQuery library is included at this point $(document).ready(function(){ // sec ...

Node js - Looping Through Loading

I am facing an issue with my Node.js application. It runs perfectly fine on my local environment, but when I try to run it on my server using forever, the page just keeps loading without displaying anything. There seems to be no response and it gets stuc ...

Issue with disabled button in Angular 2 when using Chrome's autocomplete feature

In a basic login form, the login button is initially disabled with the following code: [disabled]="!password || !loginName" When Chrome's autocomplete feature fills in the values for loginName and password, the button remains disabled after the pa ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

ng-hide is not functioning to display the form

I'm trying to display a form using ng-if when the "add" button is clicked, but it's not working. I've looked at several examples and tried them all, but none have worked for me. Here is the code I am using: angular.module('myFormApp&ap ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

In search of a tool that enables horizontal scrolling of content

I am on the lookout for a piece of Javascript code that can be integrated into my website to enable me to horizontally scroll content either from left to right or right to left. Although I found this script here: It offers the fundamental functionality th ...

Jquery issue: Lightbox unexpectedly closing by itself :(

Help needed: My light box is closing automatically within seconds. $(document).ready(function(){ $('.lightbox').click(function(){ $('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear'); ...

Placeholder image for content background

Is it possible to set a background image specifically for a content placeholder? Currently, I can display a background image for the entire page, but the content placeholder covers most of the picture. I would like to set a background image for the content ...