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 ;)
Related
I am working on form(input field) validation.
Problem - IE browsers(8-9) consider the placeholder text as value and during validation it accepts the same value, however it should be considered as an empty value. I don't wanna use any script and to achieve it, I came up with below function. Can anybody improve the usability/scope of the function little bit more. Currently it makes input field blank everytime user enters the value. However, I want it to validate for first time when placeholder default text comes into action. Any suggestion?
HTML
<input type="text" name="memberid" id="memberid" placeholder="Some Value" />
Search
jQuery
$('#search-btn').on('click', function(){
if($.browser.msie){
$('input').each(function() {
var theAttribute = $(this).attr('placeholder');
if (theAttribute) {
$(this).val('');
alert('Please enter value - IE');
}
});
}
});
placeholder creates problem in < IE 9 so you can use data() like
HTML
<input type="text" name="memberid" id="memberid" data-placeholder="Some Value" placeholder="Some Value"/>
SCRIPT
$('#search-btn').on('click', function(){
if($.browser.msie){
$('input').each(function() {
var theAttribute = $(this).data('placeholder');
if (theAttribute == this.value) {// check placeholder and value
$(this).val('');
alert('Please enter value - IE');
}
});
}
});
I think the best way to achieve what you want to do is to build a complete solution for placeholders in IE8 and IE9. To do that, what I suggest is to use Modernizr, with the input placeholder function detection. So, you could use a function like this:
window.ie8ie9placeholders = function() {
if (!Modernizr.input.placeholder) {
return $("input").each(function(index, element) {
if ($(element).val() === "" && $(element).attr("placeholder") !== "") {
$(element).val($(element).attr("placeholder"));
$(element).focus(function() {
if ($(element).val() === $(element).attr("placeholder")) {
return $(element).val("");
}
});
return $(element).blur(function() {
if ($(element).val() === "") {
return $(element).val($(element).attr("placeholder"));
}
});
}
});
}
};
This will enable placeholders for IE8 and IE9. All you need to do is to use it when you initialize your code.
ie8ie9placeholders();
I am using the following script to change the HTML5 required attribute of my input elements. I am wonder whether there is a way to modify this script to make it also work in Safari browsers, since Safari does not support this attribute.
Here is the script:
$(document).ready(function() {
$_POST = array();
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field can't be blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
You can also do this:
var valid = true;
$('input[required]').each(function() {
if (this.value == '') {
// Alert or message to let them know
valid = false;
return false; // stop on first error, or remove this and it'll go through all of them.
}
});
if (valid === false) {
return false;
}
Check out this page here. It contains a hacky solution that should add the desired functionality
http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
You're going to need to run the check yourself using an event handler on your form submission. In that handler, you run the check yourself, and if it fails, you display whatever error message and block the submission using preventDefault or return false.
An example can be found here, though as it notes, you need to be careful if you use checkValidity as your means of checking the form.
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.
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.
Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);