Instructions on changing class when input length is not equal to zero

Is there a way to dynamically add a class to an input[type="email"] when its length is greater than 0 and remove it when the input length reaches 0?

I'm not very proficient in JavaScript, so the solution could be implemented using vue.js or pure JavaScript.

Despite attempting some examples found online, I have not been successful in finding a working solution.

<div class="form-group">
  <input type="email" name="email" required>
  <label for="email">Email</label>
</div>
  • Add a class if the input length is greater than 0
  • Remove the class if the input length equals 0

Answer №1

In terms of manipulating the class of a div element, there are different approaches depending on whether you are using jQuery or pure Javascript.

$(document).on("change", "input", function(){
    if($(this).val().length > 0) {
        $("div").addClass("form-group");
    } else {
        $("div").removeClass("form-group");
    }
});

For those who prefer pure Javascript, a similar functionality can be achieved:

<div id="myDiv" class="form-group">
  <input id="myInput" type="email" name="email" onChange="checkValue()" required>
  <label for="email">Email</label>
</div>

The corresponding Javascript code would be:

function checkValue(){
   if(document.getElementById("myInput").value.length > 0){
      document.getElementById("myDiv").classList.add("form-group");
   } else {
      document.getElementById("myDiv").classList.remove("form-group");
   }
}
checkValue(); //Initial check to determine if input is empty

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 is the method for adding two elements to an array?

Currently, I am using JavaScript to push elements into an array. As a result, the output looks like this: ["api", "management", "provision", "tenant", "external", "provider"] => Correct Now, after pushing data into the array, I want to append two el ...

Charting with multiple series

I am exploring a unique approach to creating a timeline chart. I am seeking advice on the best way to implement this in the world of JavaScript. My challenge is to create interactive milestones with descriptive text displayed on the Y axis, while displayi ...

What is the best way to access a specific attribute of an object that is within an array in JavaScript or Google Apps Script?

One challenge I'm facing is with a javascript function that generates an array filled with objects. Each object contains various attributes such as id, colour, and size. After the array is created, it is sent to a Google Apps Script for further proces ...

GET requests will not be allowed

Having an unusual issue where the GET parameters are not being passed properly. <!DOCTYPE html> <html> <body> <?php var_dump($_GET); var_dump($_POST); ?> <form action="test.php?ds=1" m ...

Is there a method to manually generate a cookie for Internet Explorer using InnoSetup?

Is there a way to manually create a cookie in InnoSetup on behalf of a specific website, such as www.stackoverflow.com, similar to how JavaScript cookies are stored? Javascript cookie: function setCookie(cname,cvalue,exdays) { var d = new Date(); d.s ...

Enhance your slideshows with React-slick: Integrate captivating animations

I recently built a slider using react slick, and now there is a need to adjust the transition and animation of slides when the previous and next buttons are clicked. I received some advice to add a class to the currently active slide while changing slide ...

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

What is the best approach to designing a reusable/global button component in Nuxt.js or Vue.js?

We've all encountered this scenario before. Writing good code involves avoiding repetition. If you find yourself using the same code in multiple files, consider turning it into a component. Trust your own judgement to determine when it's necessar ...

Encountering an Unresolved Runtime Issue: TypeError arises when attempting to access properties of undefined (specifically 'call') while utilizing the Image component in next.js

I'm currently experimenting with the Image component offered by next.js. This Is My Basic Header Component import Image from 'next/image' import React from 'react' import myImage from '../assets/IMG-20221115-WA0001.jpg' ...

Limiting the table width in TinyMCE

Currently, I am utilizing TinyMCE within a Vue application. I've set up TinyMCE with the table_grid: false configuration, causing a dialog to appear when a table is created. This dialog allows users to specify rows, columns, width, and more. Within t ...

Assign a value to a text input using React

Whenever the closeEmail function is triggered or called, I need to set the email.emailAddress as the value of the textfield. I'm fairly new to React, what is the syntax or method to achieve this? Any suggestions? #code snippet <div style={{ disp ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Identifying rectangular shapes in an image and overlaying a div on top using Jquery

I am currently exploring the possibility of achieving the following: Imagine having an image within a div (serving as the background image). This image resembles an Excel sheet. My goal is to generate an input tag or contenteditable div when a user clicks ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

The error message "res.jwt is not a function" is commonly encountered when using Node

I kept receiving the error message: res.jwt is not a function I have installed jwt-express and imported it like this: import jwt from 'jwt-express' This is my auth.js file: import Account from '../services/account.js' import env from ...

Is it possible to use v-html without adding an extra wrapping tag?

When working with vue 2, the v-html directive usually requires an extra wrapping tag. However, I am attempting to do something different as shown below. <select v-model="coutnry"> // here the options to be rendered. </select> <s ...

iOS users may find that when a web page loads, it is often already scrolled halfway down

Encountering a problem with a long-scroll website that I'm currently developing. Whenever I access the page on my iPhone, the initial scroll position is consistently halfway down or near the bottom of the page. I've attempted to troubleshoot by d ...

Tips for inserting a hyperlink on every row in Vuetables using VUE.JS

Trying to implement a link structure within each row in VUEJS Vuetables has been challenging for me. Despite my research on components and slots, I am struggling to add a link with the desired structure as shown below: <td class="text-center"> <a ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Issue with VueJS and ESlint (prettier) displaying error message "adjacent JSX elements need to be enclosed in a parent tag"

Help needed with my linter/prettier setup in VueJS. Encountering a parsing error in every .vue file, specifically occurring at the <script> or <style> tag following the <template> ... </template>) Error message: Parsing error: Une ...