How i can show only pdf,doc,docx format when click file upload - html

I am trying to block all extension except doc, docx and pdf by my code it's like accept for only google chrome
this is my code:
<input type="file" id="filedocxpdf" name="filedocxpdf" class="txtNotice" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>

This might help u!
Javascript Solution
var myfile="";
$('#button_id').click(function( e ) {
e.preventDefault();
$('#filedocxpdf').trigger('click');
});
$('#filedocxpdf').on( 'change', function() {
myfile= $( this ).val();
var ext = myfile.split('.').pop();
if(ext=="pdf" || ext=="docx" || ext=="doc"){
alert(ext); return true;
} else{
alert(ext); return false;
}
});
Alternate Solution 2
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".docx", ".doc", ".pdf");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
</script>
<input type="file" id="filedocxpdf" onchange="checkfile(this);" />

Other browsers ignore such an accept attribute, though e.g.
Firefox for example, supports some simple cases like accept="image/gif".
You need to create a Javascript solution to check the file extension :
var file = document.getElementById('someId');
file.onchange = function(e){
var ext = this.value.match(/\.([^\.]+)$/)[1];
switch(ext)
{
case 'jpg':
case 'bmp':
case 'png':
case 'tif':
alert('allowed');
break;
default:
alert('not allowed');
this.value='';
}
};
example Here

Related

Show the uploaded file on the home page [duplicate]

I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.
How can I do this?
imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}
<form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.
Here's an example:
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.
<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
</script>
One-liner solution:
The following code uses object URLs, which is much more efficient than data URL for viewing large images (A data URL is a huge string containing all of the file data, whereas an object URL, is just a short string referencing the file data in-memory):
<img id="blah" alt="your image" width="100" height="100" />
<input type="file"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
Generated URL will be like:
blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345
Try This
To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.
It needs an "onChange" event to load the image.
function preview() {
frame.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="frame" src="" width="100px" height="100px"/>
</form>
To preview multiple image click here
The answer of LeassTaTT works well in "standard" browsers like FF and Chrome.
The solution for IE exists but looks different. Here description of cross-browser solution:
In HTML we need two preview elements, img for standard browsers and div for IE
HTML:
<img id="preview"
src=""
alt=""
style="display:none; max-width: 160px; max-height: 120px; border: none;"/>
<div id="preview_ie"></div>
In CSS we specify the following IE specific thing:
CSS:
#preview_ie {
FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)
}
In HTML we include the standard and the IE-specific Javascripts:
<script type="text/javascript">
{% include "pic_preview.js" %}
</script>
<!--[if gte IE 7]>
<script type="text/javascript">
{% include "pic_preview_ie.js" %}
</script>
The pic_preview.js is the Javascript from the LeassTaTT's answer. Replace the $('#blah') whith the $('#preview') and add the $('#preview').show()
Now the IE specific Javascript (pic_preview_ie.js):
function readURL (imgFile) {
var newPreview = document.getElementById('preview_ie');
newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;
newPreview.style.width = '160px';
newPreview.style.height = '120px';
}
That's is. Works in IE7, IE8, FF and Chrome. Please test in IE9 and report.
The idea of IE preview was found here:
http://forums.asp.net/t/1320559.aspx
http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85).aspx
Short two-liner
This is size improvement of cmlevy answer - try
<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])">
<img id="pic" />
I have edited #Ivan's answer to display "No Preview Available" image, if it is not an image:
function readURL(input) {
var url = input.value;
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
var reader = new FileReader();
reader.onload = function (e) {
$('.imagepreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('.imagepreview').attr('src', '/assets/no_preview.png');
}
}
Here's a multiple files version, based on Ivan Baev's answer.
The HTML
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
JavaScript / jQuery
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
Requires jQuery 1.8 due to the usage of $.parseHTML, which should help with XSS mitigation.
This will work out of the box, and the only dependancy you need is jQuery.
Yes. It is possible.
Html
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br/>
<img id="thumbnil" style="width:20%; margin-top:10px;" src="" alt="image"/>
JS
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img=document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
You can get Live Demo from here.
Clean and simple
JSfiddle
This will be useful when you want The event to triggered indirectly from a div or a button.
<img id="image-preview" style="height:100px; width:100px;" src="" >
<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">
<button onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>
<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
var fileinputElement = document.getElementById(hidden_input_image);
fileinputElement.click();
}
</script>
TO PREVIEW MULTIPLE FILES using jquery
$(document).ready(function(){
$('#image').change(function(){
$("#frames").html('');
for (var i = 0; i < $(this)[0].files.length; i++) {
$("#frames").append('<img src="'+window.URL.createObjectURL(this.files[i])+'" width="100px" height="100px"/>');
}
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="file" id="image" name="image[]" multiple /><br/>
<div id="frames"></div>
</body>
Example with multiple images using JavaScript (jQuery) and HTML5
JavaScript (jQuery)
function readURL(input) {
for(var i =0; i< input.files.length; i++){
if (input.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $('<img id="dynamic">');
img.attr('src', e.target.result);
img.appendTo('#form1');
}
reader.readAsDataURL(input.files[i]);
}
}
}
$("#imgUpload").change(function(){
readURL(this);
});
}
Markup (HTML)
<form id="form1" runat="server">
<input type="file" id="imgUpload" multiple/>
</form>
In React, if the file is in your props, you can use:
{props.value instanceof File && (
<img src={URL.createObjectURL(props.value)}/>
)}
How about creating a function that loads the file and fires a custom event. Then attach a listener to the input. This way we have more flexibility to use the file, not just for previewing images.
/**
* #param {domElement} input - The input element
* #param {string} typeData - The type of data to be return in the event object.
*/
function loadFileFromInput(input,typeData) {
var reader,
fileLoadedEvent,
files = input.files;
if (files && files[0]) {
reader = new FileReader();
reader.onload = function (e) {
fileLoadedEvent = new CustomEvent('fileLoaded',{
detail:{
data:reader.result,
file:files[0]
},
bubbles:true,
cancelable:true
});
input.dispatchEvent(fileLoadedEvent);
}
switch(typeData) {
case 'arraybuffer':
reader.readAsArrayBuffer(files[0]);
break;
case 'dataurl':
reader.readAsDataURL(files[0]);
break;
case 'binarystring':
reader.readAsBinaryString(files[0]);
break;
case 'text':
reader.readAsText(files[0]);
break;
}
}
}
function fileHandler (e) {
var data = e.detail.data,
fileInfo = e.detail.file;
img.src = data;
}
var input = document.getElementById('inputId'),
img = document.getElementById('imgId');
input.onchange = function (e) {
loadFileFromInput(e.target,'dataurl');
};
input.addEventListener('fileLoaded',fileHandler)
Probably my code isn't as good as some users but I think you will get the point of it. Here you can see an example
Following is the working code.
<input type='file' onchange="readURL(this);" />
<img id="ShowImage" src="#" />
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#ShowImage')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
Try this
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
What about this solution?
Just add the data attribute "data-type=editable" to an image tag like this:
<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />
And the script to your project off course...
function init() {
$("img[data-type=editable]").each(function (i, e) {
var _inputFile = $('<input/>')
.attr('type', 'file')
.attr('hidden', 'hidden')
.attr('onchange', 'readImage()')
.attr('data-image-placeholder', e.id);
$(e.parentElement).append(_inputFile);
$(e).on("click", _inputFile, triggerClick);
});
}
function triggerClick(e) {
e.data.click();
}
Element.prototype.readImage = function () {
var _inputFile = this;
if (_inputFile && _inputFile.files && _inputFile.files[0]) {
var _fileReader = new FileReader();
_fileReader.onload = function (e) {
var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;
var _img = $("#" + _imagePlaceholder);
_img.attr("src", e.target.result);
};
_fileReader.readAsDataURL(_inputFile.files[0]);
}
};
//
// IIFE - Immediately Invoked Function Expression
// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready
(
function (yourcode) {
"use strict";
// The global jQuery object is passed as a parameter
yourcode(window.jQuery, window, document);
}(
function ($, window, document) {
"use strict";
// The $ is now locally scoped
$(function () {
// The DOM is ready!
init();
});
// The rest of your code goes here!
}));
See demo at JSFiddle
Preview multiple images before it is uploaded using jQuery/javascript?
This will preview multiple files as thumbnail images at a time
Html
<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"
accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input" value="">
<div id="divImageMediaPreview"></div>
Script
$("#ImageMedias").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#divImageMediaPreview");
dvPreview.html("");
$($(this)[0].files).each(function () {
var file = $(this);
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "width: 150px; height:100px; padding: 10px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
Working Demo on Codepen
Working Demo on jsfiddle
I hope this will help.
<img id="blah" alt="your image" width="100" height="100" />
<input type="file" name="photo" id="fileinput" />
<script>
$('#fileinput').change(function() {
var url = window.URL.createObjectURL(this.files[0]);
$('#blah').attr('src',url);
});
</script>
To Preview MULTIPLE Files and Single file in single function with reusable approach using Plain JavaScript
function imagePreviewFunc(that, previewerId) {
let files = that.files
previewerId.innerHTML='' // reset image preview element
for (let i = 0; i < files.length; i++) {
let imager = document.createElement("img");
imager.src = URL.createObjectURL(files[i]);
previewerId.append(imager);
}
}
<input accept="image/*" type='file' id="imageInput_1"
onchange="imagePreviewFunc(this, imagePreview_1)" />
<div id="imagePreview_1">This Div for Single Image Preview</div>
<hr />
<input class="form-control" accept="image/*" type='file' id="imageInput_2" multiple="true"
onchange="imagePreviewFunc(this, imagePreview_2)" />
<div id="imagePreview_2">This Div for Multiple Image Preview</div>
I have made a plugin which can generate the preview effect in IE 7+ thanks to the internet, but has few limitations. I put it into a github page so that its easier to get it
$(function () {
$("input[name=file1]").previewimage({
div: ".preview",
imgwidth: 180,
imgheight: 120
});
$("input[name=file2]").previewimage({
div: ".preview2",
imgwidth: 90,
imgheight: 90
});
});
.preview > div {
display: inline-block;
text-align:center;
}
.preview2 > div {
display: inline-block;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js"></script>
Preview
<div class="preview"></div>
Preview2
<div class="preview2"></div>
<form action="#" method="POST" enctype="multipart/form-data">
<input type="file" name="file1">
<input type="file" name="file2">
<input type="submit">
</form>
For Multiple image upload (Modification to the #IvanBaev's Solution)
function readURL(input) {
if (input.files && input.files[0]) {
var i;
for (i = 0; i < input.files.length; ++i) {
var reader = new FileReader();
reader.onload = function (e) {
$('#form1').append('<img src="'+e.target.result+'">');
}
reader.readAsDataURL(input.files[i]);
}
}
}
http://jsfiddle.net/LvsYc/12330/
Hope this helps someone.
It's my code.Support IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3
function previewImage(fileObj, imgPreviewId) {
var allowExtention = ".jpg,.bmp,.gif,.png"; //allowed to upload file type
document.getElementById("hfAllowPicSuffix").value;
var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
var browserVersion = window.navigator.userAgent.toUpperCase();
if (allowExtention.indexOf(extention) > -1) {
if (fileObj.files) {
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById(imgPreviewId).setAttribute("src", e.target.result);
};
reader.readAsDataURL(fileObj.files[0]);
} else if (browserVersion.indexOf("SAFARI") > -1) {
alert("don't support Safari6.0 below broswer");
}
} else if (browserVersion.indexOf("MSIE") > -1) {
if (browserVersion.indexOf("MSIE 6") > -1) {//ie6
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
} else {//ie[7-9]
fileObj.select();
fileObj.blur();
var newPreview = document.getElementById(imgPreviewId);
newPreview.style.border = "solid 1px #eeeeee";
newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
newPreview.style.display = "block";
}
} else if (browserVersion.indexOf("FIREFOX") > -1) {//firefox
var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
if (firefoxVersion < 7) {//firefox7 below
document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());
} else {//firefox7.0+ 
document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
}
} else {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}
} else {
alert("only support" + allowExtention + "suffix");
fileObj.value = ""; //clear Selected file
if (browserVersion.indexOf("MSIE") > -1) {
fileObj.select();
document.selection.clear();
}
}
}
function changeFile(elem) {
//file object , preview img tag id
previewImage(elem,'imagePreview')
}
<input type="file" id="netBarBig" onchange="changeFile(this)" />
<img src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>
Default Iamge
#Html.TextBoxFor(x => x.productModels.DefaultImage, new {#type = "file", #class = "form-control", onchange = "openFile(event)", #name = "DefaultImage", #id = "DefaultImage" })
#Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { #class = "text-danger" })
<img src="~/img/ApHandler.png" style="height:125px; width:125px" id="DefaultImagePreview"/>
</div>
<script>
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var output = document.getElementById('DefaultImagePreview');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
Here's a solution if you're using React:
import * as React from 'react'
import { useDropzone } from 'react-dropzone'
function imageDropper() {
const [imageUrl, setImageUrl] = React.useState()
const [imageFile, setImageFile] = React.useState()
const onDrop = React.useCallback(
acceptedFiles => {
const file = acceptedFiles[0]
setImageFile(file)
// convert file to data: url
const reader = new FileReader()
reader.addEventListener('load', () => setImageUrl(String(reader.result)), false)
reader.readAsDataURL(file)
},
[setImageFile, setImageUrl]
)
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })
return (
<div>
<div {...getRootProps()}>
{imageFile ? imageFile.name : ''}
{isDragActive ? <p>Drop files here...</p> : <p>Select image file...</p>}
<input {...getInputProps()} />
</div>
{imageUrl && (
<div>
Your image: <img src={imageUrl} />
</div>
)}
</div>
)
}
https://stackoverflow.com/a/59985954/8784402
ES2017 Way
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
Here is a much easy way to preview image before upload using pure javascript;
//profile_change is the id of the input field where we choose an image
document.getElementById("profile_change").addEventListener("change", function() {
//Here we select the first file among the selected files.
const file = this.files[0];
/*here i used a label for the input field which is an image and this image will
represent the photo selected and profile_label is the id of this label */
const profile_label = document.getElementById("profile_label");
//Here we check if a file is selected
if(file) {
//Here we bring in the FileReader which reads the file info.
const reader = new FileReader();
/*After reader loads we change the src attribute of the label to the url of the
new image selected*/
reader.addEventListener("load", function() {
dp_label.setAttribute("src", this.result);
})
/*Here we are reading the file as a url i.e, we try to get the location of the
file to set that as the src of the label which we did above*/
reader.readAsDataURL(file);
}else {
//Here we simply set the src as default, whatever you want if no file is selected.
dp_label.setAttribute("src", "as_you_want")
}
});
And here is the HTML;
<label for="profile_change">
<img title="Change Profile Photo" id="profile_label"
src="as_you_want" alt="DP" style="height: 150px; width: 150px;
border-radius: 50%;" >
</label>
<input style="display: none;" id="profile_change" name="DP" type="file" class="detail form-control">
for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null.
Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
function assignFilePreviews() {
$('input[data-previewable=\"true\"]').change(function() {
var prvCnt = $(this).attr('data-preview-container');
if (prvCnt) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = $('<img>');
img.attr('src', e.target.result);
img.error(function() {
$(prvCnt).html('');
});
$(prvCnt).html('');
img.appendTo(prvCnt);
}
reader.readAsDataURL(this.files[0]);
}
}
});
}
$(document).ready(function() {
assignFilePreviews();
});
HTML
<input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
<div class = "prd-img-prv"></div>
This also handles case when file with invalid type ( ex. pdf ) is choosen

how can i change the html code in crm form?

I used dynamics CRM 2015 and i want to change the OptionSet type to checkboxs.
Just like this:
enter image description here
My solution is use JQuery get the td tag in crm form,and use html() change the td html code.
Like this $("#ubg_note_d").html().But question comes that i can't get the td tag which i want to display the checkbox.Only after i used the browser DEVELOPER TOOLS and select the element,then i can get the tag......i have blocked by this for 1 day,any helps?;)
note:i tried the js and jquery,both can't get the td tag.My code is run in the form Onload event,and i tried the filed Onchange event,trouble still there...
Thing you are trying to achieve is unsupported. Instead you can achieve the same using supported way by creating html web resource, which can be added on form on later.
Code for web resource is as below.
<html><head>
<title></title>
<script type="text/javascript" src="new_jquery_1.10.2.js"></script>
<script type="text/javascript">
// function will be called when web resource is loaded on Form.
$(document).ready(function () {
ConvertDropDownToCheckBoxList();
});
//Coverts option list to checkbox list.
function ConvertDropDownToCheckBoxList() {
var dropdownOptions = parent.Xrm.Page.getAttribute("new_makeyear").getOptions();
var selectedValue = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
$(dropdownOptions).each(function (i, e) {
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '') {
if (selectedValue != null && selectedValue.indexOf(rvalue) != -1)
isChecked = true;
var checkbox = "< input type='checkbox' name='r' / >" + rText + ""
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.click(function () {
//To Set Picklist Select Values
var selectedOption = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
if (this.checked) {
if (selectedOption == null)
selectedOption = rvalue;
else
selectedOption = selectedOption + "," + rvalue
}
else {
var tempSelected = rvalue + ",";
if (selectedOption.indexOf(tempSelected) != -1)
selectedOption = selectedOption.replace(tempSelected, "");
else
selectedOption = selectedOption.replace(rvalue, "");
}
parent.Xrm.Page.getAttribute("new_selectedyears").setValue(selectedOption);
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute("new_selectedyeartext").getValue();
if (this.checked) {
if (selectedYear == null)
selectedYear = rText;
else
selectedYear = selectedYear + "," + rText
}
else {
var tempSelectedtext = rText + ",";
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
parent.Xrm.Page.getAttribute("new_selectedyeartext").setValue(selectedYear);
})
.appendTo(checkboxList);
}
});
}
</script>
<meta charset="utf-8">
</head><body>
<div id="checkboxList">
</div>
</body></html>
Refer below given link for
enter link description here
No code needed for that. It's just configuration on CRM to change the display format : checkbox.

Primefaces PhotoCam Camera Selection

how could I enable camera selection on primefaces photocam ?
Here is what I have done presently without luck ( image not rendering... )
<pm:content>
<script>
jQuery(document).ready(function() {
'use strict';
var videoElement = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
function gotSources(sourceInfos) {
for (var i = 0; i !== sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
var option = document.createElement('option');
option.value = sourceInfo.id;
if (sourceInfo.kind === 'audio') {
} else if (sourceInfo.kind === 'video') {
option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined' ||
typeof MediaStreamTrack.getSources === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
MediaStreamTrack.getSources(gotSources);
}
function successCallback(stream) {
window.stream = stream; // make stream available to console
videoElement.src = window.URL.createObjectURL(stream);
videoElement.play();
}
function errorCallback(error) {
console.log('navigator.getUserMedia error: ', error);
}
function start() {
videoElement = document.querySelector('video');
if (!!window.stream) {
videoElement.src = null;
window.stream.stop();
}
var videoSource = videoSelect.value;
var constraints = {
audio: false,
video: {
optional: [{
sourceId: videoSource
}]
}
};
navigator.getUserMedia(constraints, successCallback, errorCallback);
}
videoSelect.onchange = start;
start();
});
</script>
<p:outputLabel value="Seleccione Camara:" />
<select id="videoSource"></select>
<p:photoCam widgetVar="pc" listener="#{eventoMB.oncapture}" update="photo" />
I am trying to achieve this goal by using javascript but the problem something is preventing the change proposed here, which I could not identify up to know...
Thanks for your attention.
Well in case someone needs this information:
in attach function(c) after these lines ( around line 89 from primefaces-5.2.jar\META-INF\resources\primefaces\photocam\photocam.js ) :
b.style.transform = "scaleX(" + h + ") scaleY(" + g + ")"
}
c.appendChild(b);
I added the following lines:
var constraints = {
audio: false,
video: {
facingMode: {
exact: "environment"
}
}
};
this.video = b;
var i = this;
navigator.getUserMedia(constraints, function(j) {
Note that specifing facingMode for the video constraints apparently does the trick in firefox for android and google only in the desktop version apparently as stated here:
GetUserMedia - facingmode
By the way it would be interesting to me to discuss if this solution is the more appropiate thing to do or there is a better one.
Hope this helps someone else, thanks anyway.

Polyfill HTML5 form attribute (for input fields)

This is the markup I use:
<input type="text" form="myform" name="inp1" />
<form id="myform" name="myform">
...
</form>
Now I realized that it does not work for old IE and therefore I am searching for a HTML 5 polyfill.
Anyone aware of a certain polyfill which covers this HTML5 feature?
I wrote this polyfill to emulate such feature by duplicating fields upon form submission, tested in IE6 and it worked fine.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var sampleElement = $('[form]').get(0);
var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
The polyfill above doesn't take into account the Edge browser. I have amended it to use feature detection, which I have tested in IE7+, Edge, Firefox (mobile/desktop), Chrome (mobile/desktop), Safari (mobile/desktop), and Android browser 4.0.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
I improved patstuart's polyfill, such that:
a form can now be submitted several times, e.g. when using the target attribute (external fields were duplicated previously)
reset buttons now work properly
Here it is:
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
var CLASS_NAME_POLYFILL_MARKER = "html-5-polyfill-form-attr-marker";
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.attr('class', CLASS_NAME_POLYFILL_MARKER)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e, origSubmit) {
// clean up form from last submit
$('.'+CLASS_NAME_POLYFILL_MARKER, this).remove();
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// add data from external submit, if needed:
if (origSubmit && origSubmit.name)
data.push({name: origSubmit.name, value: origSubmit.value})
// append data to form
$(this).appendField(data);
})
//submit and reset behaviour
$('button[type=reset], input[type=reset]').click(function() {
//extend reset buttons to fields with matching form attribute
// reset form
var formId = $(this).attr("form");
var formJq = $('#'+formId);
if (formJq.length)
formJq[0].reset();
// for elements outside form
if (!formId)
formId = $(this).closest("form").attr("id");
$fields = $('[form=' + formId + ']');
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
});
$('button[type=submit], input[type=submit], input[type=image]').click(function() {
var formId = $(this).attr("form") || $(this).closest("form").attr("id");
$('#'+formId).trigger('submit', this); //send clicked submit as extra parameter
});
})(jQuery);
after reading thru the docs of webshim it seems it has a polyfill for that.
http://afarkas.github.io/webshim/demos/demos/webforms.html
I made a vanilla JavaScript polyfill based on the above polyfills and uploaded it on GitHub: https://github.com/Ununnilium/form-attribute-polyfill.
I also added a custom event to handle the case when submit is processed by JavaScript and not directly by the browser. I tested the code only shortly with IE 11, so please check it yourself before use. The polling should maybe be replaced by a more efficient detection function.
function browserNeedsPolyfill() {
var TEST_FORM_NAME = "form-attribute-polyfill-test";
var testForm = document.createElement("form");
testForm.setAttribute("id", TEST_FORM_NAME);
testForm.setAttribute("type", "hidden");
var testInput = document.createElement("input");
testInput.setAttribute("type", "hidden");
testInput.setAttribute("form", TEST_FORM_NAME);
testForm.appendChild(testInput);
document.body.appendChild(testInput);
document.body.appendChild(testForm);
var sampleElementFound = testForm.elements.length === 1;
document.body.removeChild(testInput);
document.body.removeChild(testForm);
return !sampleElementFound;
}
// Ideas from jQuery form attribute polyfill https://stackoverflow.com/a/26696165/2372674
function executeFormPolyfill() {
function appendDataToForm(data, form) {
Object.keys(data).forEach(function(name) {
var inputElem = document.createElement("input");
inputElem.setAttribute("type", "hidden");
inputElem.setAttribute("name", name);
inputElem.value = data[name];
form.appendChild(inputElem);
});
}
var forms = document.body.querySelectorAll("form[id]");
Array.prototype.forEach.call(forms, function (form) {
var fields = document.querySelectorAll('[form="' + form.id + '"]');
var dataFields = [];
Array.prototype.forEach.call(fields, function (field) {
if (field.disabled === false && field.hasAttribute("name")) {
dataFields.push(field);
}
});
Array.prototype.forEach.call(fields, function (field) {
if (field.type === "reset") {
field.addEventListener("click", function () {
form.reset();
Array.prototype.forEach.call(dataFields, function (dataField) {
if (dataField.nodeName === "SELECT") {
Array.prototype.forEach.call(dataField.querySelectorAll('option'), function (option) {
option.selected = option.defaultSelected;
});
} else {
dataField.value = dataField.defaultValue;
dataField.checked = dataField.defaultChecked;
}
});
});
} else if (field.type === "submit" || field.type === "image") {
field.addEventListener("click", function () {
var obj = {};
obj[field.name] = field.value;
appendDataToForm(obj, form);
form.dispatchEvent(eventToDispatch);
});
}
});
form.addEventListener("submit", function () {
var data = {};
Array.prototype.forEach.call(dataFields, function (dataField) {
data[dataField.name] = dataField.value;
});
appendDataToForm(data, form);
});
});
}
// Poll for new forms and execute polyfill for them
function detectedNewForms() {
var ALREADY_DETECTED_CLASS = 'form-already-detected';
var newForms = document.querySelectorAll('form:not([class="' + ALREADY_DETECTED_CLASS + '"])');
if (newForms.length !== 0) {
Array.prototype.forEach.call(newForms, function (form) {
form.className += ALREADY_DETECTED_CLASS;
});
executeFormPolyfill();
}
setTimeout(detectedNewForms, 100);
}
// Source: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
function polyfillCustomEvent() {
if (typeof window.CustomEvent === "function") {
return false;
}
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
if (browserNeedsPolyfill()) {
polyfillCustomEvent(); // IE is missing CustomEvent
// This workaround is needed if submit is handled by JavaScript instead the browser itself
// Source: https://stackoverflow.com/a/35155789/2372674
var eventToDispatch = new CustomEvent("submit", {"bubbles": true, "cancelable": true});
detectedNewForms(); // Poll for new forms and execute form attribute polyfill for new forms
}
I take some time to send an update for this polyfill because it doesn't work with MS Edge.
I add 2 line to fix it :
var isEdge = navigator.userAgent.indexOf("Edge");
if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11 && isEdge == -1) {
// browser supports it, no need to fix
return;
}
UPDATE: Edge now support it:
https://caniuse.com/#feat=form-attribute

How to support placeholder attribute in IE8 and 9

I have a small issue, the placeholder attribute for input boxes is not supported in IE 8-9.
What is the best way to make this support in my project (ASP Net). I am using jQuery.
Need I use some other external tools for it?
Is http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html a good solution?
You could use this jQuery plugin:
https://github.com/mathiasbynens/jquery-placeholder
But your link seems to be also a good solution.
You can use any one of these polyfills:
https://github.com/jamesallardice/Placeholders.js (doesn't support password fields)
https://github.com/chemerisuk/better-placeholder-polyfill
These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!
the $.Browser.msie is not on the latest JQuery anymore...
you have to use the $.support
like below:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
if you use jquery you can do like this. from this site Placeholder with Jquery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
these are the alternate links
Placeholder jquery library
HTML5 polyfills -- go for placeholder section
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
try this
I use thisone, it's only Javascript.
I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.
You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!
You can use a placeholder in a password input by setting the type of the original password input to text.
Tinker: http://tinker.io/4f7c5/1
- JSfiddle servers are down!
*sorry for my bad english
JAVASCRIPT
function removeValue() {
document.getElementById('mailcontainer')
.innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
document.getElementById('email').focus(); }
HTML
<span id="mailcontainer">
<input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
For others landing here. This is what worked for me:
//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Just add this in you script.js file.
Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.
function fix_placeholder(container){
if(container == null) container = document.body;
if(!('placeholder' in document.createElement('input'))){
var inputs = container.getElements('input');
Array.each(inputs, function(input){
var type = input.get('type');
if(type == 'text' || type == 'password'){
var placeholder = input.get('placeholder');
input.set('value', placeholder);
input.addClass('__placeholder');
if(!input.hasEvent('focus', placeholder_focus)){
input.addEvent('focus', placeholder_focus);
}
if(!input.hasEvent('blur', placeholder_blur)){
input.addEvent('blur', placeholder_blur);
}
}
});
}
}
function placeholder_focus(){
var input = $(this);
if(input.get('class').contains('__placeholder') || input.get('value') == ''){
input.removeClass('__placeholder');
input.set('value', '');
}
}
function placeholder_blur(){
var input = $(this);
if(input.get('value') == ''){
input.addClass('__placeholder');
input.set('value', input.get('placeholder'));
}
}
I confess that it looks a bit more MORE than others but it works fine.
__placeholder is a ccs-class to make the color of the placeholder text fancy.
I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.
Hope you like it.
Kind regards.
I used the code of this link
http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Add the below code and it will be done.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field's styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>