Simple way to check if placeholder is supported? - javascript

I want to use the HTML5 "placeholder" attribute in my code if the user's browser supports it otherwise just print the field name on top of the form. But I only want to check whether placeholder is supported and not what version/name of browser the user is using.
So Ideally i would want to do something like
<body>
<script>
if (placeholderIsNotSupported) {
<b>Username</b>;
}
</script>
<input type = "text" placeholder ="Username">
</body>
Except Im not sure of the javascript bit. Help is appreciated!

function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
I used a jQuery-ized version as a starting point. (Just giving credit where it's due.)

Or just:
if (document.createElement("input").placeholder == undefined) {
// Placeholder is not supported
}

Another way without making an input element in memory that has to be GC'd:
if ('placeholder' in HTMLInputElement.prototype) {
...
}

If you are using Modernizr, quick catch following:
if(!Modernizr.input.placeholder){
...
}

http://html5tutorial.info/html5-placeholder.php has the code to do it.
If you're already using jQuery, you don't really need to do this though. There are placeholder plugins available ( http://plugins.jquery.com/plugin-tags/placeholder ) that will use the HTML5 attribute where possible, and Javascript to simulate it if not.

I'm trying to do the same... here i wrote this
if(!('placeholder'in document.createElement("input"))){
//... document.getElementById("element"). <-- rest of the code
}}
With this you should have an id to identify the element with the placeholder...
I don't know thought if this also help you to identify the element ONLY when the placeholder isn't supported.

Hi there this is an old question but hopefully this helps someone.
This script will check the compatibility of placeholders in your browser, and if its not compatible it will make all input fields with a placeholder use the value="" field instead. Note when the form is submitted it will also change your input back to "" if nothing was entered.
// Add support for placeholders in all browsers
var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);
if (testPlaceholderCompatibility === false)
{
$('[placeholder]').load(function(){
var input = $(this);
if (input.val() == '')
{
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
});
$('[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().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}

A bit late to the party, but if you're using jQuery or AngularJS you can simplify the method suggested above without using any plugins.
jQuery
typeof $('<input>')[0].placeholder == 'string'
AngularJS
typeof angular.element('<input>')[0].placeholder == 'string'
The checks are very similar, as AngularJS runs jQlite under the hood.

NOTE: Placeholder DO NOT work in internet explorer in a way, it should work.
document.createElement("input").placeholder == undefined
Doesnt work in internet explorer 11 - document.createElement("input").placeholder return empty string
var testInput = document.createElement('input');
testPlaceholderCompatibility = ('placeholder' in testInput);
Doesnt work in internet explorer 11 - return true
'placeholder'in document.createElement("input")
Doesnt work in internet explorer 11 - return true
In theory, Internet explorer 11 is supposed to support placeholder, but in fact - when input get focus placeholder disappear. In Chrome placeholder showed until you actually type something, no matter on focus.
So, feature detection doesnt work in this case - you need to detect IE and show Labels.

Related

Place holder is not working

Place holder is not working in IE-9,so I used the below code for place holder.
jQuery(function () {
debugger;
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
When I am taking the value of test,it shows null.How can I get the details of all input tag?
I think this will help you
if ($.browser.msie) {
$("input").each(function () {
if (IsNull($(this).val()) && $(this).attr("placeholder") != "") {
$(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
$(this).keypress(function () {
if ($(this).hasClass('hasPlaceHolder')) $(this).val("").removeClass('hasPlaceHolder');
});
$(this).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
});
}
});
}
I'm on my mobile so this is hard but really you need to do
JQuery.support.placeholder = typeof 'placeholder' in test !== 'undefined'
Because null means there isn't any placeholder value, but there is placeholder support
From what I understand you're saying that the placeholder in test is returning null
I suggest you don't write this yourself and go for an off-the-shelf solution. There's more complexity here that you'd probably want to tackle yourself if all you want is provide support for older browsers.
For example, here's the shim I'm using (and that is recommended on http://html5please.com): https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js
Go ahead and read the code. These are some issues you need to have in mind when writing such shim:
detect the browser support,
keep track when the box contains the real input or not;
add a class to allow different text colour for the placeholder,
clear the placeholders before submitting the form,
clear the placeholders when reloading the page,
handle textarea,
handle input[type=password]
And that's probably not even all. (The library I've linked also hooks into jQuery in order to make .val() return '' when there's no real input in the box.
There's also another shim that uses a totally different approach: https://github.com/parndt/jquery-html5-placeholder-shim/blob/master/jquery.html5-placeholder-shim.js
This library doesn't touch the actual value of the input, but instead displays an element directly over it.
HTML:
<input type='text' id='your_field' value='Enter value'/>
jQuery:
$(document).ready(function(){
$("#your_field").on('focusout',function(){
if($("#your_field").val() == ''){
$("#your_field").val('Enter value');
}
});
$("#your_field").on('focus',function(){
if($("#your_field").val() == 'Enter value'){
$("#your_field").val('');
}
});
});
See DEMO
Also check when the form is posted because if the user submits the form without entering the field then Enter value will be posted as the value of the field.So do either validations in client side or check in the server side when submitting the form.

Is there a js function I could use that would make the placeholder attribute work in IE? [duplicate]

This question already has answers here:
Input placeholders for Internet Explorer
(17 answers)
Closed 9 years ago.
Right now I have a bunch of input tags in my project that use a placeholder, like this:
<input id="Name" name="Name" placeholder="Name Goes Here" type="text" value="">
Is there a js function that I could place in my global js script that would change the input tag if the browser is IE?
For example, if the browser was internet explorer, I could run a specific javascript function that would change ALL my placeholders to something that IE uses (if that even exists)
// Detect the browser, as you want. I'm using the follwowing way
var browserName=navigator.appName;
if (browserName=="Microsoft Internet Explorer")
{
replacePlHolders();
}
// replace all the placeholders with a simple text input
function replacePlHolders()
{
var plInps = $("input[placeholder]");
plInps.each(function(){
var name=$(this).attr("name");
var newInput = $("<input type='text' name='"+name+"' value='"+name+" goes here'>");
$(this).replaceWith(newInput);
var defaultValue = name + " goes here";
newInput.on('focus', function() {
// If this value of the input equals our sample,
// hide it when the user clicks on it.
if(this.value === defaultValue)
this.value = '';
});
newInput.on('blur', function() {
// When they click off of the input, if
// the value is blank, bring back the sample.
if(this.value === '')
this.value = defaultValue;
});
});
}
Place this code in your global Javascript file and this will do the magic for you.
Check the fiddle here
Please check out jquery-html5-placeholder-shim
if(!Modernizr.input.placeholder){
$('[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('');
}
});
});
}

Simple jQuery form Validation: Checking for empty .val() failing in ie9 due to placeholder polyfill

New Issue / Answer
I am using an HTML5 placeholder polyfill which is causing ie9 to set the input's placeholder text as the value. So while in HTML5 browsers the val attribute is empty, in the below code ie9 is seeing it as filled in.
I'm using jQuery to make sure all fields are filled in. This works fine in ie10, webkit, and mozilla but fails in ie9.
What am I doing wrong here, and why won't this code work in ie9?
Thank you!
$('#quoteform .button.next').on('click',function(){
var $me = $(this),
$myParent = $me.parent(),
$nextStep = $myParent.nextAll('fieldset:not(.disabled)').first(),
validate;
// If we're on step2, make sure all fields are filled in
if($me.is('#quote-step2 .button') || $me.is('#quote-step1 .button')) {
$me.parents('fieldset').find('input:visible').each(function(){
var $me = $(this),
myVal = this.value;
if(myVal === '') {
$me.parent().addClass('warning');
validate = false;
return;
} else {
if(typeof validate === 'undefined')
validate = true;
}
});
}
if(validate === false) {
alert('Please fill out all fields before continuing.');
return false;
}
switchView($nextStep, $myParent);
});
I ran into a similar issue and my workaround was to also test the value against the placeholder string in addition to testing for an empty value. Since the polyfill replaces the input's value with the placeholder string the empty value is the value of the placeholder in IE9.
$me.parents('fieldset').find('input:visible').each(function(){
var $me = $(this),
myVal = this.value,
myPlaceholder = $me.attr('placeholder');
if(myVal === '' || myVal === myPlaceholder) {
$me.parent().addClass('warning');
validate = false;
return;
} else {
if(typeof validate === 'undefined')
validate = true;
}
});

Webkit checkbox default value is null?

When using a WebKit browser (Chrome or Safari), if I try to get the default value of a checkbox, it returns "". However, the same javascript in Firefox or IE will return "on".
So lets say I have this checkbox on a page:
<input type="checkbox" id="chkDefaultValue">
I use this javascript to return all "input" elements on a page
var elems = document.getElementsByTagName('input');
Then I go through a loop that gets the value like this
elems[i].getAttribute('value')
When elems[i] is that checkbox, in Chrome or Safari it returns "", but Firefox or IE it returns "on".
Is there any way to use Javascript to return the "on" value in Safari or Chrome? In Chrome I use a jquery call that uses .val() and that actually returns "on", but I need a way to do this using Javascript in Safari.
Thanks!
EDIT:
I'm actually looking for the "value" attribute specifically since the "value" of a checkbox can be anything, like "cat" or "bike".
Use checked instead to see if a checkbox or radio input is selected.
If what you really want to do is get the value attribute, and not see if the checkbox is selected, then you need to set a value for the checkbox first. If nothing is set then you getting null is the normal behavior.
You can also replicate the Firefox and IE behavior by assigning on yourself as a default value:
var myVal = elems[i].getAttribute('value');
if(myVal === null)
myVal = 'on';
I think that it's because elems[i].getAttribute('value') is not what you should be using to get the state of a checkbox.
Try using elems[i].getAttribute('checked') or just elems[i].checked to get the state.
By the way, elems[i].getAttribute('value') can be shortened to just elems[i].value.
Just read your comment on another answer...
Here's the source for the .val() statement from the jQuery repo:
getVal = function(elem)
{
var type = elem.type, val = elem.value;
if (type === "radio" || type === "checkbox")
{
val = elem.checked;
} else if (type === "select-multiple") {
val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) {return elem.selected;}).join("-"):"";
} else if (elem.nodeName.toLowerCase() === "select") {
val = elem.selectedIndex;
}
return val;
}
That is pretty simple JavaScript, and you can just omit the .map() function.
Also, why not just test for the existence of the value property?
function niceValue(element)
{
if (element.value != '')
{
return element.value;
} elseif (element.checked) {
if (element.checked)
{
return 'on';
} else {
return 'off';
}
}
}
Good luck!

Implementing placeholder="" for opera through jquery

I have implemented through jQuery the placeholder HTML 5 attribute for the browsers that don't support it (all except webkit at this time).
It works really great but it has a small problem: it breaks the HTML 5 required="required" and pattern="pattern" attributes on Opera (it's the only browser that supports them currently).
This is because the placeholder value is temporarily set as the input value, and thus Opera thinks on form submission that the input is actually filled with the placeholder value. So I decided to remove the placeholders when the form is submitted:
$('form').submit(function() {
$(this).find(".placeholder").each(function() {
$(this).removeClass('placeholder');
$(this).val('');
});
});
This worked but another problem arose: if the form client-side validation failed (because of the required or pattern attributes) then the fields aren't re-given their placeholder value.
So, is there a way (js event?) to know if/when the form submission failed client-side, so I can re-add the placeholders?
Test case: open this with a browser that supports required/pattern but not placeholder (only Opera at this time). Try to submit the form without filling any of the inputs; you'll see that when you do the second input loses the placeholder. I don't want it to happen.
This is the complete code, but it's probably not needed:
function SupportsPlaceholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
$(document).ready(function() {
if (SupportsPlaceholder())
return;
$('input[placeholder]').focus(function() {
if ($(this).hasClass('placeholder')) {
if ($(this).val() == $(this).attr('placeholder'))
$(this).val('');
$(this).removeClass('placeholder');
}
});
$('input[placeholder]').keypress(function() {
if ($(this).hasClass('placeholder')) {
if ($(this).val() == $(this).attr('placeholder'))
$(this).val('');
$(this).removeClass('placeholder');
}
});
$('input[placeholder]').blur(function() {
if ($(this).val() != '')
return;
$(this).addClass('placeholder');
$(this).val($(this).attr('placeholder'));
});
$('input[placeholder]').each(function() {
if ($(this).val() != '' && $(this).val() != $(this).attr('placeholder'))
return;
$(this).val($(this).attr('placeholder')).addClass('placeholder');
});
$('form').submit(function() {
$(this).find(".placeholder").each(function() {
$(this).removeClass('placeholder');
$(this).val('');
});
});
});
read this: http://dev.opera.com/articles/view/making-legacy-pages-work-with-web-forms/
I didn't try, but it looks like you can check form validity this way:
if (form.checkValidity ){// browser supports validation
if( ! form.checkValidity()){ // form has errors,
// the browser is reporting them to user
// we don't need to take any action
}else{ // passed validation, submit now
form.submit();
}
}else{ // browser does not support validation
form.submit();
}
or simply check: element.validity.valid
btw. you should implement placeholder also for textarea - simply replace 'input[placeholder]' with 'input[placeholder], textarea[placeholder]'... and actually you don't need 'placeholder' class ;)

Categories