Obtain the value of "Placeholder" using JavaScript in Internet Explorer without the need for JQuery

I have some custom Javascript code that checks for browser support of placeholders and creates them if not supported. This solution works on some older browsers, but not all, especially IE.

The issue I am facing is retrieving the "Placeholder" value; currently in IE9, it returns "undefined".

Below is my current code:

//Check if Placeholders are supported
var test = document.createElement("input");
if ("placeholder" in test) {
  var testholder = true;
} else {
  var testholder = false;
}

//Fix unsupported Placeholder functionality
function placeHolder(id)
{
    var demo = document.getElementById(id);

    demo.className = "fix-hint";
    demo.value = demo.placeholder;

    demo.onfocus = function()
    {
        if (this.className == "fix-hint")
        { 
          this.value = ""; 
          this.className = "fix-nohint"; 
        }
    };

    demo.onblur = function()
    {
        if (this.value === "")
        { 
          this.className = "fix-hint"; 
          this.value = demo.placeholder; 
        }
    };
    return false;
}

I prefer using pure Javascript without JQuery as JQuery can be bulky for small tasks, and I want to improve my understanding of Javascript. Although Modernizr is an option for future use, I am not currently utilizing it.

UPDATE

This updated code has been successfully tested in IE 8 and 9. The function call is placed within an if/else condition for "placeSupport".

//Check if placeholders are supported

placeholderSupport = ("placeholder" in document.createElement("input"));
if (!placeholderSupport) {
  var placeSupport = false;
} else {
    var placeSupport = true;
}

//Add placeholder support for older browsers

function placeHolder(id)
{
  var el = document.getElementById(id);
  var placeholder = el.getAttribute("placeholder");

  el.onfocus = function ()
  {
      if(this.value == placeholder)
      {
          this.value = '';
          this.className = "fix-nohint";
      }
  };

  el.onblur = function ()
  {
      if(this.value.length == 0)
      {
          this.value = placeholder;
          this.className = "fix-hint";
      }
  };

  el.onblur();
}

}

Answer №1

If you're uncertain about using specific functionality/attributes, try checking out caniuse.com - you'll find that placeholder is not supported in IE9.

Consider utilizing getAttribute("placeholder")

The getAttribute() method retrieves the value of a specified attribute on the designated element. If the attribute does not exist, it will return either null or "" (an empty string); refer to Notes for more information.

EXAMPLE

HTML

<input id="demo" placeholder="Rawr" />

JavaScript

var placeholder = document.getElementById("demo").getAttribute("placeholder");
console.log(placeholder);

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

Is there a way to retrieve the form name within my directive?

In my code, I am able to retrieve the ngModel name, but now I am looking for a way to also capture the form's name that contains the element with the "validacion" directive. It is crucial for me to programmatically obtain the form's name where t ...

Anticipate that the function will remain inactive when the screen width is less than 480 pixels

Implementing Functionality in Responsive Navigation <script> document.addEventListener('DOMContentLoaded', () => { let windowWidth = window.Width; let withinMobile = 480; let close = document.getElementById('close&ap ...

When the URL is modified, triggering an event to load

Is there a way to make a page load directly to a specific section and automatically open an accordion? For instance, I have a page with multiple accordions displayed vertically. I already know that using id's in the URL like page#accordion1 will scro ...

Use jQuery to dynamically update a text field within a table row based on a selection from

My understanding of JS and jQuery is not very strong. This is the HTML Output I created using a foreach-loop: $('#ProjectOfferPosition0IsystemTypeVariantId').on('change', function () { var prices = []; prices[1] = 500.00; ...

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...

An error occurred while trying to import a module due to an unexpected token

Take a look at this codepen link I encountered an error (line 10 in index.vue) with the following import: import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js"; Any idea what could be causing this issue? All other ...

Issue with Angular UI-Router nested views: Content not displaying

I'm attempting to incorporate nested views for a webpage using angular ui-router. I have set up the state definitions according to various tutorials, but I am unable to display any content in the child views. Surprisingly, there are no errors showing ...

Guide to updating passwords with passport-local-mongoose

After successfully importing the passport-local-mongoose to my code and being able to register and log in users, I now face the challenge of changing the password for a specific user. How can I achieve this? According to the documentation of passport-local ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

Reasons Why Vue Component Does Not Update When Select Changes

I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle: http ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

Is there a way to customize the ripple effect color on a Button?

As I'm exploring the API (v3.9.2), I have noticed a reference to TouchRippleProps for ButtonBase on https://material-ui.com/api/button-base/ The code for my button is as follows: <Button variant="text" size={"large"} ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Angular/JS - setTimeout function is triggered only upon the occurrence of a mouse click

I'm currently working on a website that calculates the shortest path between two points in a grid utilizing AngularJS. Although I have already implemented the algorithm and can display the colored path, I am facing an issue where the color changes ti ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Customize the popover in React Material-UI to your liking

I am currently utilizing a Select component within my application. https://i.stack.imgur.com/hjXlY.png I have created a custom modal component that I wish to display instead of the default list items when the select is clicked. Is there a method to overr ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...