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

Ways to empty an angularJS array

let itemList = ['X', 'Y', 'Z']; Even though the array is cleared, the user interface does not reflect the change. itemList = []; This method solves the issue. But why? itemList.length = 0; ...

External JavaScript file not executing defined function

My homepage includes a register form that should open when the register button is clicked. However, I am encountering an issue where the function responsible for opening the form from another JavaScript file is not being triggered. Here is the HTML code: ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

What is the counterpart of the JavaScript transport.responseText in jQuery's Ajax requests?

I'm currently in the process of converting my JavaScript Ajax request to jQuery's ajax. Here is an example of my existing JavaScript Ajax code: new Ajax.Request(url, { method: 'post', onSuccess: function(transport) { ...

The useEffect hook in Next.js does not trigger a re-render when the route changes

I'm currently experiencing an issue with a useEffect inside a component that is present in every component. I've implemented some authentication and redirection logic in this component, but I've noticed that when using Next.js links or the b ...

Arrange a series by the actual pixel width of the string

Imagine you have an array of tags represented as strings and you need to display them in a narrow view. Some tags are smaller, allowing for 2 to fit on one line, while larger tags require their own line. Your goal is to sort the array so that the smalles ...

What is the best way to utilize a single AngularJS 1.5 component multiple times within a single view?

While working on a project using AngularJS 1.5's new components, I encountered an issue with widget isolation. It seems that when I use the same widget multiple times, they end up sharing their controller or scope. I was under the impression that comp ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...

Displaying varied information based on JSON feedback using AngularJS

I am currently in the process of developing an app using AngularJS and the Ionic framework. The app will display a list of data with various subcategories for each item, depending on the account type. View sample image here The issue I am facing is that ...

What is the best way to pass JSON data into a JavaScript function?

As a beginner in javascript, I have been struggling to find a solution for my problem for a week. The code example I am working with is shown below (all within an HTML page in the head tag) //example function 1 function randomString(len, charSet) { ...

Having trouble using the `.not` function in jQuery

I'm working on implementing a collapsible menu using jQuery. When any header is clicked, the next sibling (the box) should expand while all other boxes collapse. HTML <div class="finbox" id="finbox1"> <div class="finheader" id="finheade ...

Using JavaScript to Set Values and Manage Session State in APEX

Trying to utilize JavaScript in Oracle APEX to set the value and session state. See below function that is being called: function updateItemValue(element) { $s('P2020_SELECTED', element); apex.server.process ('MY_PROCESS', { ...

Ways to gradually reveal all elements within a header section

Is there a way to gradually reveal all the components in my header once the window has finished loading by utilizing jQuery's fadeIn function? Below is the pertinent code snippet: HTML <div class="banner"> <header class="header"> < ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

What steps can I take to ensure that my Onetrust consent script is properly loaded before implementing Facebook pixel tracking in NextJS?

Looking for a solution to load my Cookies consent script as the first script in our NextJS application. The problem arises because we have Facebook pixel tracking implemented and they use parentNode.insertBefore which places their script on top. This is h ...

Utilize AngularJS to bind keys to arrays

Hey there, I have an array that looks like this: $scope.Selectedgroups =[183,184,24] I want to convert it to the format shown below: [{groupId:183},{groupId:184},{groupId:24}]; I've been trying to convert it using a for loop: var groups=[] ...

How to implement caching using XMLHttpRequest?

As someone who has primarily relied on jQuery's AjAX method, I am relatively new to using XMLHttpRequests. However, due to performance concerns in a web worker environment, I now find myself having to resort to the classic XMLHttpRequest. Currently, ...

Utilize AJAX or another advanced technology to refine a pre-existing list

I am trying to implement a searchable list of buttons on my website, but I haven't been able to find a solution that fits exactly what I have in mind. Currently, I have a list of buttons coded as inputs and I want to add a search field that will filte ...

Challenges with Asset Management in Vite Compilation Result

I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames option to categorize assets into subfolders based on their types (css, fonts, img, js), but it&apos ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...