How to support placeholder attribute in IE8 and 9 - html

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>

Related

Button hide and show reset

Hello I have a question I want to reset button if the fields are empty, the reset is not displayed if a value is entered, the reset is displayed
Reset
for jquery ill recomand this
$( "input" ).change(function() {
var val = $(this).val();
if(val == ""){
$("#yourresetbutton").hide();
}else{
$("#yourresetbutton").show();
}
});
I'm not sure what you mean by this but I take it you want a button to appear only if a textbox if left blank. If so you this is some code you can use:
<input id='textbox' type='text'></input>
<button id='resetButton'></button>
setInterval(checkText, 10)
function checkText() {
if(document.getElementById('textbox').value == '') {
document.getElementById('resetButton').visibility = 'visible';
}
else() {
document.getElementById('resetButton').visibility = 'hidden';
}
}

Edge Browser input placeholder (text duplicated)

This is the html:
<input id="testInput" placeholder="something" />
UPDATED
found this piece of javascript overriding how the "placeholder" attribute works. It seems that it is failing to override it in the Edge browser.
define(['jquery'], function ($) {
(function ($) {
var default_options = {
labelClass: 'placeholder'
};
var ph = "PLACEHOLDER-INPUT";
var phl = "PLACEHOLDER-LABEL";
var boundEvents = false;
/*
//using custom placeholder for all browsers now: partials/_formBasics.scss
//check for browser support for placeholder attribute
var input = document.createElement("input");
if('placeholder' in input) {
$.fn.placeholder = $.fn.unplaceholder = function () { }; //empty function
delete input;
return;
};
delete input;
*/
$.fn.placeholder = function (options) {
bindEvents();
var opts = $.extend(default_options, options);
this.each(function () {
var rnd = Math.random().toString(32).replace(/\./, ''),
input = $(this),
label = $('<label style="position:absolute; z-index:100; "></label>');
if (!input.attr('placeholder') || input.data(ph) === ph) return;
//make sure the input tag has an ID assigned, if not, assign one.
if (!input.attr('id')) {
input.attr('id', 'input_' + rnd);
}
label.attr('id', input.attr('id') + "_placeholder").data(ph, '#' + input.attr('id')) //reference to the input tag
.attr('for', input.attr('id')).addClass(opts.labelClass).addClass(opts.labelClass + '-for-' + this.tagName.toLowerCase()) //ex: watermark-for-textarea
.addClass(phl).text(input.attr('placeholder'));
input.data(phl, '#' + label.attr('id')) //set a reference to the label
.data(ph, ph) //set that the field is watermarked
.addClass(ph) //add the watermark class
.before(label); //add the label field to the page
itemOut.call(this);
});
//$('label').disableSelection();
};
$.fn.unplaceholder = function () {
this.each(function () {
var input = $(this),
label = $(input.data(phl));
if (input.data(ph) !== ph) return;
label.remove();
input.removeData(ph).removeData(phl).removeClass(ph);
});
};
function bindEvents() {
if (boundEvents) return;
$(document).on('click, focusin, change', '.' + ph, itemIn);
$(document).on('focusout', '.' + ph, itemOut);
$(document).on('keyup', '.' + ph, itemKeyStroke);
bound = true;
boundEvents = true;
};
function itemIn() {
var input = $(this),
label = $(input.data(phl));
if ($(input).val().length > 0)
$(label).addClass('hasValue').removeClass('FocusNoValue');
else
$(label).addClass('FocusNoValue').removeClass('hasValue');
};
function itemOut() {
var input = $(this),
label = $(input.data(phl));
if ($(input).val().length > 0)
$(label).addClass('hasValue').removeClass('FocusNoValue');
else
$(label).removeClass('FocusNoValue').removeClass('hasValue');
};
function itemKeyStroke() {
var input = $(this),
label = $(input.data(phl));
if ($(input).val().length > 0)
$(label).addClass('hasValue').removeClass('FocusNoValue');
else
$(label).addClass('FocusNoValue').removeClass('hasValue');
};
} (jQuery)); //placeholder
});
It is not just in Edge that the jQuery custom placeholder was not working. It was also looking poor in Firefox. That's because the plugin needs CSS too. The comment about browser support says that the relevant CSS is in this SASS file: partials/_formBasics.scss. I recommended tweaking that SASS in order to support the new Edge browser.
As an example, this fiddle fixes it in both Edge and Firefox by adding some CSS. These are the CSS classes that the plugin uses:
placeholder
placeholder-for-input
PLACEHOLDER-LABEL
hasValue
FocusNoValue
You do not need to use them all. The fiddle added only the following. We hide the placeholder, align the label, and hide the label when appropriate.
label.placeholder {
color:red;
font-family:arial;
/* hide the placeholder */
background-color:white;
/* align the label */
margin-top:0.1rem;
margin-left:0.1rem;
font-size:0.9rem;
}
label.hasValue, label.FocusNoValue {
/* hide the label when appropriate */
display:none !important;
}
Fixed result in Edge

What is the alternative of placeholder in html for xhtml?

What is the XHTML equivalent of HTML placeholder.
placeholder is new in HTML 5.
There is no equivalent in XHTML 1.x (which is the XML version of HTML 4.x)
It is, of course, available in the XML serialisation of HTML 5.
Failing that, you would have to fake it using JavaScript (which is probably best done by absolutely positioning a second <label> element under the <input> which you set to have a transparent background colour unless it has a value or the focus).
I did a experiment to simulate the placeholder using xhtml+js+css as happen on HTML5 placeholder property.
xhtml:
<input id="textbox-obj" type="text" class="search-txt" data-placeholder="Search" title="Search something here">
Javascript (jquery):
//Function to place the textbox cursor to the begining
function moveCursorToStart(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = 0;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(true);
range.select();
}
}
function initSearchTextPlaceholder(textBox) {
textBox.focus(function() {
if( $(this).val() == $(this).attr('data-placeholder') ) {
moveCursorToStart(this);
// To fix Chrome's bug
window.setTimeout(function() {
moveCursorToStart(this);
}, 1);
}
}).blur(function() {
if( $(this).val() == $(this).attr('data-placeholder') || $(this).val() == '' ) {
$(this).addClass('placeholder').val($(this).attr('data-placeholder'));
}
}).on('keypress', function() {
if( $(this).val() == $(this).attr('data-placeholder') ) {
$(this).removeClass('placeholder').val('');
}
}
).blur();
}
initSearchTextPlaceholder($("#textbox-obj"));
CSS
.search-txt {
color: #333;
}
.search-txt.placeholder {
color: #8d8d8d;
}

Email input form not showing/working properly in different browsers

I have a simple form which only has two input controls: a text box for taking emails, and a submit button.
HTML:
<form class="form-wrapper cf">
<input type="text" placeholder="Enter your email here..." required>
<button type="submit">
Submit
</button>
</form>
JSFiddle: http://jsfiddle.net/ahmadka/aDhUL/
Form has issues in different browsers:
Chrome: Works & displays fine.
iPhone: Works & displays fine.
Firefox 22: placeholder text not shown, and cannot type anything in
the textbox too !
Internet Explorer 10: Works fine, but placeholder text is cropped !
How can I make it cross-browser compatible guys ?
I've tried removing the placeholder and required parameters to make it very simple, but still it doesn't work on Firefox ..
I think you try to run "placeholder" in all browser.
then just attach one .js file that as follow it work Fine in all browser.
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
and then just put one script on page.
<script>
$(function() {
$('input, textarea').placeholder();
});
</script>
It Work Fine in All Browser (placeholder)
Actually the problem is with your CSS styling.
You have set the height of the input as 0px. So the input box accepts the input but is not displayed in FF due to the height set to zero.
Your Previous Code is here:
.form-wrapper input {
width: 150px;
height: 0px;
padding: 10px 5px;
New JSFiddle with height set to 10px is here: http://jsfiddle.net/B435n/
And you can use any jQuery plugin for placeholder thing.

How to validate pattern matching in textarea?

When I use textarea.checkValidity() or textarea.validity.valid in javascript with an invalid value both of those always return true, what am I doing wrong?
<textarea name="test" pattern="[a-z]{1,30}(,[a-z]{1,30})*" id="test"></textarea>​
jQuery('#test').on('keyup', function() {
jQuery(this).parent().append('<p>' + this.checkValidity() + ' ' +
this.validity.patternMismatch + '</p>');
});
http://jsfiddle.net/Riesling/jbtRU/9/
HTML5 <textarea> element does not support the pattern attribute.
See the MDN doc for allowed <textarea> attributes.
You may need to define this functionality yourself.
Or follow the traditional HTML 4 practice of defining a JavaScript/jQuery function to do this.
You can implement this yourself with setCustomValidity().
This way, this.checkValidity() will reply whatever rule you want to apply to your element.
I don't think this.validity.patternMismatch can set manually, but you could use your own property instead, if needed.
http://jsfiddle.net/yanndinendal/jbtRU/22/
$('#test').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
This will enable the pattern attribute on all textareas in the DOM and trigger the Html5 validation. It also takes into account patterns that have the ^ or $ operators and does a global match using the g Regex flag:
$( document ).ready( function() {
var errorMessage = "Please match the requested format.";
$( this ).find( "textarea" ).on( "input change propertychange", function() {
var pattern = $( this ).attr( "pattern" );
if(typeof pattern !== typeof undefined && pattern !== false)
{
var patternRegex = new RegExp( "^" + pattern.replace(/^\^|\$$/g, '') + "$", "g" );
hasError = !$( this ).val().match( patternRegex );
if ( typeof this.setCustomValidity === "function")
{
this.setCustomValidity( hasError ? errorMessage : "" );
}
else
{
$( this ).toggleClass( "error", !!hasError );
$( this ).toggleClass( "ok", !hasError );
if ( hasError )
{
$( this ).attr( "title", errorMessage );
}
else
{
$( this ).removeAttr( "title" );
}
}
}
});
});
In case there are others who use React-Bootstrap HTML form validation and not jQuery.
This does not explicitly use pattern but it works the same way.
I'm only making some changes from the documentation.
function FormExample() {
const [validated, setValidated] = useState(false);
const [textArea, setTextArea] = useState('');
const textAreaRef = useRef(null);
const handleSubmit = (event) => {
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
};
const isValid = () => {
// Put whichever logic or regex check to determine if it's valid
return true;
};
useEffect(() => {
textAreaRef.current.setCustomValidity(isValid() ? '' : 'Invalid');
// Shows the error message if it's invalid, remove this if you don't want to show
textAreaRef.current.reportValidity();
}, [textArea];
return (
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Row>
<Form.Group md="4" controlId="validationCustom01">
<Form.Label>Text area</Form.Label>
<Form.Control
required
as="textarea"
ref={textAreaRef}
placeholder="Text area"
value={textArea}
onChange={(e) => setTextArea(e.target.value)}
/>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Form.Group>
</Form.Row>
<Button type="submit">Submit form</Button>
</Form>
);
}
render(<FormExample />);