Utilizing JavaScript to apply a CSS style when a text field is devoid of any content

Within my JavaScript code, I have a function called using an onclick event in the HTML:

function validateTextField(field) {
if (field.value == '') {
    sheet.insertRule("input:focus {background: #fc9fff;}", 1);
  }
}

To test if the condition statement is working correctly, I replaced the insertRule with an alert message and found that the CSS is being applied even when the field is not empty. Are there any alternative methods I can use?

Answer №1

The issue arises when the check method is triggered with an empty element, resulting in the addition of a general rule for input:focus. This rule remains even after focus has been removed from the current element.

An improved approach would involve utilizing a class such as

function checkTextField(field) {
    if (field.value == '') {
        field.classList.add('empty')
    } else {
        field.classList.remove('empty')
    }
}

and then in your stylesheet

input.empty:focus {
    background: #fc9fff;
}

Answer №2

If you want to style required and invalid input fields using only CSS, you can utilize the :required and :invalid selector in combination with setting the required attribute on the field.

<style>
   input:required:invalid { background: #fc9fff; }      
</style>

<input name="email" required />

To see this in action, check out the live version here: http://jsfiddle.net/devotis/z319pp1f/

While it may seem a bit harsh to make all required fields red at first glance, it does provide clear visual feedback for users.

Answer №3

It seems like your question is a bit unclear to me, but I have created a test HTML file and it appears to be functioning properly:

<html>
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style></style>
    <script>
var styleAlreadyAppended = false;
function checkTextField(field) {
    var sheet = document.styleSheets[0];
    if (field.value == '' && styleAlreadyAppended !== true) {
        sheet.insertRule("input:focus {background: #f30;}", 0);
        styleAlreadyAppended = true;
    }
    else if (field.value != '' && styleAlreadyAppended === true) {
        sheet.deleteRule(0);
    }
}
    </script>
</head>
<body>
    <div>
        <input id="testinput" type="text" value="">
        <button onclick="checkTextField(document.getElementById('testinput'))">test</button>
    </div>
</body>
</html>

This code was tested on the Firefox browser version 36.

Answer №4

Perhaps a more effective strategy would be to link your function to the onchange event in the following manner:

<input type="text" onchange="checkTextField" />

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

Access the Android mobile application by using a JavaScript click event

I have been attempting to launch an installed android mobile application from an html page in the Chrome browser using a javascript or jQuery click function. While an anchor tag tap works perfectly and opens the installed app, I have encountered issues wh ...

How can I rotate around the local axis of an object using THREEJS?

I'm struggling to grasp the concept of local axis rotation in ThreeJS. Despite referencing this Rotate around local axis answer, I can't seem to achieve the desired outcome. For example, if I create a cylinder and rotate it const geometry = new ...

How about crafting a brand new div element?

Creating a new div using JavaScript should be simple, but I'm struggling with it. I've seen many solutions online, but none seem to work for me. I want to generate a new div element, assign it an ID, and style it using CSS. I have tried using doc ...

Having trouble with a Vue3 project after running a Vite build in production mode?

When I run my project in development mode, everything works perfectly fine. However, when I build the project using `vite build´, some components stop functioning. Oddly enough, there are no errors displayed in the console or in the build logs. If I use ...

To ensure proper formatting, I must include a comma operator for numbers while typing and limit the decimal places to two

Could someone assist me in formatting a number to include commas and restrict the decimal places to two using regex? I have attempted the following, but need help making it work properly. Currently, when I enter a number it shows up as 1231244, however I ...

Does MongoDB have a method to identify the presence of an element within an array?

I am currently working on a query where I need to ensure that a specific string does not appear in an array. The schema I am using looks like this: _id: { type: String, required: true }, ... meta: { user_likes: { ...

Locate the presence of a specific key within a JSON object

"questions": [{ "_id": "5b2bc4f6f1dacd2b0ca65bca", "updatedAt": "2018-06-21T15:32:06.237Z", "createdAt": "2018-06-21T15:32:06.237Z", "title": "What is the meaning of RC?", "answer": "opt4", "testId": "5b2bbcc ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

What is the best way to display a placeholder image in a React project when the image URL is

Here is the code snippet I'm working with: import React, { Component } from 'react'; import './App.css'; class App extends Component { state = { loaded: false, error: false } onImageLoad = () => { this.setS ...

Is it beneficial to remove margins in CSS?

As I dive deeper into studying CSS and practicing my skills, I've encountered a common issue where the first element on top often requires margin or padding adjustments in certain browsers. So, my question is: Is it considered good practice to use th ...

Tips for protecting a Javascript SQLite local database

I am looking to implement a local database with SQlite for offline data access. The data should only be accessed by a specific JS application, and I want to prevent other applications or malicious users from peeking into the database. I am considering encr ...

What is the most effective method to align two elements within a container in CSS? (one on the left and one on the right of the container)

I need help with positioning two colored box elements within a container using CSS. You can see my test page here: The code for the content in the center area of the website is as follows: HTML/CSS code: #header2 { background-color: #DEB887; } ...

Removing an element in JSON is resulting in an element that is undefined

Dealing with a JSON Object, I am faced with a challenge where deleting elements results in undefined entries, causing issues in my usage within datatables. Here is my current approach: function dTable(presId){ var allregos = '[{"presId": "a09N0000 ...

Issues with Bootstrap 4 Carousel not showing up on webpage

I've been attempting to integrate a bootstrap carousel into my HTML page. Below is the code snippet I obtained from the Bootstrap website here: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> ...

Obtain the value or values of radio buttons based on certain conditions

Recently, I have been delving into .JS and grappling with pre-existing code. One of the challenges I face involves extracting data from radio buttons after a particular selection is made. The gist of it is related to transportation requirements. Upon indi ...

Transform JSON code from JQuery to PHP

Currently, I am in the process of translating a code snippet from JQuery to PHP for performing a json POST request to a remote server. Here is my original Jquery code: $( document ).ready(function() { $('#button').click( function() ...

Creating a large grid in React Native using the FlatList component with multiple columns

Encountering some difficulties with FlatList as I try to render numerous cells on the screen. Please refer to the following image first: Image Let's consider the scenario: A map consisting of 80 rows x 80 columns = 6400 cells A toggle button to ena ...

What is the best method for incorporating various HTML checklist items into PHP code?

I am struggling to include multiple checklist values within an if-else statement. Currently, I am only able to insert a single value into the condition even if I select multiple options. Below is my code snippet: <?php $db_host = 'localhost&a ...

Discover how TypeScript enhances JavaScript by defining Built-In Types during the compilation process

When I first delved into the world of scripting languages, JavaScript felt manageable. However, things got confusing when I shifted my focus to Angular2 with TypeScript. I soon discovered that TypeScript has the ability to define Built-In Types like strin ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...