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

Chrome users may encounter difficulty grabbing the horizontal textarea scrollbar if a border-radius has been applied

Check out this JSFiddle for more information <textarea wrap="off" rows="5" style="border-radius: 4px">aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaa aaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbbaaaaaaaaaaabbbbbbbbb aa ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Express.js response.json method can be used to render both HTML and JSON content in the

I have a router that is sending JSON data to the client as shown below: router.get('/', function(req, res, next) { UserModel.selectAllUsers(function(err, vals){ if(err){ console.log(err); } res.json({d: v ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Challenge with uploading Minio presigned URLs

I am encountering a problem with the Minio presigned URL. While I have successfully obtained the URL and used the PUT method to insert my file into my Minio bucket, I am unable to open certain file types such as jpg, png, or pdf. This is due to Minio autom ...

Best way to eliminate empty options from dropdown and ensure that required validation is functioning in AngularJS?

My dropdown is populated with owners from the owners data, but it includes an extra blank option. I need to eliminate this blank option. However, when I make the necessary changes to remove it, the required validator stops working properly. <md-input-c ...

Unable to retrieve the desired information from the jQuery AJAX request

Here is an example of a C# web method: [WebMethod] public string Greetings() { return "Greetings from the server"; } This is the jQuery AJAX code used to call the web method: $.ajax({ url: "http://10.0.2.2/SampleService/ ...

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

Calling @Url.Action multiple times does not consistently return the same results

It appears that there is a discrepancy related to jQuery/MVC3 that I have yet to figure out. If anyone could shed light on this matter, it would be greatly appreciated. Whenever I invoke an action routine multiple times, the @Url.Action routine generates ...

Incapable of composing text using the MUI SearchBar

I'm having trouble with my Material UI search bar - it's not letting me type anything into it. How can I resolve this issue? Despite trying the suggested code snippets from other answers, I keep encountering errors when integrating them into my ...

Transforming global CSS into CSS modules: A step-by-step guide

In my nextjs project, I am utilizing react-bootstrap and bootstrap which requires me to include the global css: // _app.js import 'bootstrap/dist/css/bootstrap.min.css'; The issue arises when loading a significant amount of unused css on every p ...

Experiencing a WEB3js error in a Vite, React, TypeScript application: Troubleshooting TypeError with callbackify function absence

Hey there, I've been experimenting with using web3 in a React client application (specifically with vite react-ts). When trying to call web3.eth.net.getId(), I encountered an error mentioning that callbackify is not a function. After some investigatio ...

Designing Checkboxes and Radio Buttons

I am seeking a way to customize the appearance of checked and unchecked checkboxes using images without modifying the HTML structure. I would prefer not to add labels, classes, or IDs to the elements. The provided example only works in Webkit browsers, s ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

ExpressJS does not support the 'Save' function

Working on a ticketing API using NodeJS + ExpressJS. Encountering an error when trying to modify a previously created ticket using the PUT method. Error /home/ismael/projects/nodejs-ticketing/routes/ticket.js:38 item.save(function(err){ ...

What steps should I follow to obtain the return value after invoking these functions?

I have a task that requires creating a nodejs script for two specific functions: Retrieve my public IP address. Update my public IP address on my freenom.com account for a registered domain. Currently, I have two separate scripts in place to accompl ...