I implemented the HTML 5 placeholder attribute through jQuery for browsers that do not support it (all this except for the webkit at this time).
It works fine, but it has a small problem: it breaks down the attributes of HTML 5 required="required"and pattern="pattern"at the Opera (this is the only browser that supports them at the moment).
This is because the placeholder value is temporarily set as an input value, and thus Opera thinks about the form presentation, that the input is actually filled with the placeholder value. So I decided to remove the placeholders when submitting the form:
$('form').submit(function() {
$(this).find(".placeholder").each(function() {
$(this).removeClass('placeholder');
$(this).val('');
});
});
This worked, but another problem arose: if the client-side validation of the form failed (due to requiredor attributes pattern), then the fields will not be re-set with their placeholder values.
So, is there a way (js event?) To find out if / when the form submission failed with a client-side error , so can I re-add placeholders?
Test scenario : open this with a browser that supports the required / template, but not the placeholder (only Opera at this time). Try submitting the form without filling in any entries; You will see that when you make the second entry, it loses the placeholder. I do not want this to happen.
This is the complete code, but 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('');
});
});
});