Update a script that handles input float labels to support textarea elements as well

I am looking to modify a float label script that currently works for input boxes in order to make it work for textareas. I attempted to add $fields.on("textarea", floatLabel) to the script but it did not produce the desired result. Any suggestions or assistance on this issue?

(function($){
   var $fields = $(".floatLabel");

   // when data is entered...
   $fields.on("input", floatLabel);
   $fields.on("textarea", floatLabel);

   // Check the text fields as soon as the document loads for data that 
   // may have been added upon load
   floatLabel();

   function floatLabel(){
     $fields.each(function(i, f){
       var $field = $(f);
       if($field.val().trim() === "" || $field.val() === "blank"){
         $field.next().removeClass("active");
       } else {
         $field.next().addClass("active");
       }
     });
   }
})(jQuery);

CSS

.controls label.active {
    position:relative;
    top: -50px;
    left:-175px;
    color: #555;
    background-color: white;
}

.controls label {
    position: relative;
    top:0px;
    left:-175px;
    color: #999;
    font-size: 18px;
    display: inline-block;
    padding-left: 5px;
    padding-right: 5px;
    margin: 0;
    font-weight: 400;
    background-color: rgba(255, 255, 255, 0);
    pointer-events: none;
    transition: color 0.3s, top 0.3s, background-color 0.8s;
}

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-row">
  <div class="field-wrap">
    <div class="controls">
      <input type="text" class="floatLabel" name="property_address" value="<?php echo $address?>" required>
      <label for="property_address">Street Address</label>
    </div>
  </div>
  <div class="two-row">
    <div class="field-wrap">
      <div class="controls">
        <textarea name="comments" class="floatLabel">value="<?php echo $comments?>"</textarea>
        <label for="comments"></label>
      </div>
    </div>
  </div>
</div>

Answer №1

Your interpretation of the function

$fields.on("Input")

may be incorrect. It is not related to the inputbox specifically, but rather triggers on the input event, which involves receiving input. Therefore, replacing "textarea" with it does not serve any purpose since this event type is not applicable. You should consider removing that line altogether.

Furthermore, when invoking your function, you can streamline the call as follows:

$fields.on("input", floatLabel())

This eliminates the need for an additional floatLabel() interjection. As a result, the function will execute immediately upon script loading.

Edit: If the textarea lacks an 'input' event, perhaps explore using the keyup event instead?

https://api.jquery.com/keyup/

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

Vuejs responsive navbar with collapsible sidebar using Bootstrap or Bootstrap-Vue libraries

Vue.js is the framework I'm utilizing for my current project. In creating a dashboard section, I am seeking to implement a responsive design using either bootstrap, bootstrap-vue, or plain HTML and CSS. Below are the images of the desired dashboard -& ...

Similar to AngularJS, jQuery also provides a powerful tool for submitting forms

Recently, I've delved into the world of angularjs and have been truly amazed by its capabilities so far. One thing that took me by surprise was the lack of a simple solution for sending AJAX requests using the $http service. After hours of searching G ...

Adjust the size of points positioned absolutely on an image map

Are you struggling to position POIs on a picture map correctly? Check out this link for more information: Even after trying CSS scale and re-positioning in media queries, getting the points in the right place seems impossible. What do you think? Can this ...

Tips for effectively changing Observable data into an Array

I am currently attempting to transform an Observable into an Array in order to loop through the Array in HTML using ngFor. The Typescript code I have now is causing some issues. When I check the testArray Array in the console, it shows up as undefined. it ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Issue with EnumDeserializer in jackson-mapper 1.9.12 version

I'm currently working on a scenario where I need to map a String to an enum Object using the Jackson ObjectMapper.readValue(String,Class) API. The issue arises when my JSON string contains a Task Object with an Action enum defined as follows: public ...

Is it possible to utilize X-Y coordinates as repositories for values beyond just X-Y coordinates themselves?

I am in the process of creating a tile-based grid and I need to expand the X-Y coordinates to include additional values for determining characteristics of each tile, such as resources (for example, food, water, stone, lumber) within a game context. Conside ...

How do I incorporate a jcarousel slider into a thickbox popup using jQuery, HTML, and CSS?

I'm attempting to incorporate a dynamic car carousel slider into a popup that opens with Thickbox. I've made numerous attempts but haven't achieved success yet. It works when called directly in HTML, but doesn't function properly when ...

Making the Bootstrap 4 card-footer expand to occupy the remaining height of the column

I'm currently developing a project that incorporates bootstrap cards. There are 3 cards, each for a different column, and I need them to have equal heights. Here is how they currently look: https://i.sstatic.net/Nau98.png The B and C cards should oc ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

What is the best way to incorporate a custom margin within a grid system while ensuring it remains responsive?

I'm currently working on incorporating 4 non-bootstrap "cards" into my HTML layout, with some space between them. Here is an image depicting how it's supposed to look: https://i.sstatic.net/bppvW.png The problem arises when I attempt to make the ...

Storing repeated inputs in local storage multiple times

I am working on a feature where I need to store data in local storage multiple times using a dropdown menu and some input fields. Currently, I am able to retrieve all the values from the input fields and see them in the console log. My goal is to save thes ...

Is the img tag supported by html2image?

I've been diving into the functionality of the html2image package and noticed that it's having trouble locating my locally stored images. My code snippet looks like this: from html2image import Html2Image hti = Html2Image() html_str = "&q ...

Instead of sending a post request, sending an options request after the ajax request is made

Currently, I am initiating a post ajax request: var responsehttpreq = {} function createAndSendXmlHttpReq(){ requestBody = { hostname: "prova", pathname: "prova", query: "prova", method: "prova" } console.log("F ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

Modifying the display property of an element using JavaScript

Hello, I'm encountering an issue with a section of my javascript code. I am attempting to make the #showAddress element display as block when the deliverservice radio button is clicked or checked. I have tried searching for solutions on Stack Overflow ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

The authorization header for jwt is absent

Once the user is logged in, a jwt token is assigned to them. Then, my middleware attempts to validate the token by retrieving the authorization header, but it does not exist. When I try to display the request header by printing it out, it shows as undefine ...