Home > Web Front-end > JS Tutorial > Html5 placeholder attribute (IE compatible) implementation code_jquery

Html5 placeholder attribute (IE compatible) implementation code_jquery

WBOY
Release: 2016-05-16 16:38:22
Original
992 people have browsed it

HTML5 has made many enhancements to Web Form, such as new input type types, Form Validation, etc.

Placeholder is another new attribute added in HTML5. When this attribute is set in input or textarea, the content of the value will be displayed in the text box as a gray text prompt. When the text box gains focus, the prompt text disappears. In the past, this effect could only be achieved by using JavaScript. Firefox, Google Chrome, etc. expressed support for it, but IE was the only one that felt inconsistent!

For example:

Introducing a powerful attribute plug-in that allows IE to support placeholder. It is also compatible with other browsers that do not support placeholder. The code is as follows:

$(document).ready(function(){ 
 var doc=document,
 inputs=doc.getElementsByTagName('input'),
 supportPlaceholder='placeholder'in doc.createElement('input'),
 
 placeholder=function(input){
  var text=input.getAttribute('placeholder'),
  defaultValue=input.defaultValue;
  if(defaultValue==''){
  input.value=text
  }
  input.onfocus=function(){
  if(input.value===text)
  {
   this.value=''
  }
  };
  input.onblur=function(){
  if(input.value===''){
   this.value=text
  }
  }
 };
 
 if(!supportPlaceholder){
  for(var i=0,len=inputs.length;i<len;i++){
   var input=inputs[i],
   text=input.getAttribute('placeholder');
   if(input.type==='text'&&text){
    placeholder(input)
   }
  }
 }
 });
Copy after login

Just copy the code and save it as a js file for reference. No need to do any processing, super convenient!

ex: This does allow IE's Input to display the placeholder attribute, but if there is only one input on the page, it is fine. If there are multiple inputs, if the input does not fill in any value, then its empty input will automatically Fill the placeholder value into value, causing an error. For example:

<input type="text" placeholder="输入商品编码" name="goodscode" id="goodscode" value="123" />
<input type="text" placeholder="输入商品名称" name="goodsname" id="goodsname" value="输入商品名称" />
Copy after login

The solution is to make your own judgment in the background. Maybe it can be solved in the above js file and we will study it later~!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template