form fields

Simple HTML5 placeholders fallback for IE9 and older

I hoped I will never hear about IE9 and its lack of support for the placeholder attribute, … I had high hopes.

I’ve boiled a simple fallback, late in the evening and in a rush, using IE conditional comments for browser detection.

<!--[if IE 8 ]>    <html class="ie8 lt-ie10"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9 lt-ie10"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html><!--<![endif]-->
$(document).ready(function() {

	// HTML5 placeholders fallback for IE9 and older
	if ($('html').hasClass('lt-ie10')) {

		// add the placeholder text as value
		$('textarea, input:text').each(function() {
			$(this).attr('value', $(this).attr('placeholder'));
		});

		// clear form fields on focus
		$('textarea, input:text').on('focus click', function(){
			if (this.value == this.defaultValue) {
			this.value = '';
			}
		}).on('blur', function(){
			if (this.value == '') {
			this.value = this.defaultValue;
			}
		});
	}

});

Simple confirm password or email validation

If you have a form with a ‘confirm password’ field or ‘confirm email’, and you don’t want to use a heavy validation plugin just for a simple confirmation like this, you can always use some simple ‘old school’ javascript and the onblur event, so when the field loses focus triggers the validation function.

<script type="text/javascript">
	function confirmPass() {
		var pass = document.getElementById("pass").value
		var confPass = document.getElementById("c_pass").value
		if(pass != confPass) {
			alert('Wrong confirm password !');
		}
	}
</script>
<form id="form" action="" method="post">
    <label for="pass">Password</label>
    <input type="password" id="pass" class="text" name="your_pass" value=""/>
    <label for="c_pass">Confirm Password</label>
    <input type="password" id="c_pass" class="text" name="your_c_pass" value="" onblur="confirmPass()"/>
</form>

See a demo.

Clear form fields on focus

If you want to make a form without labels for text inputs or textareas, and instead give the fields default values, you will encounter a little annoying  problem, when you focus the field to write something the default value stays there. To make the default value disappear you will need a few lines of javascript.

$('textarea, input:text').bind('focus click', function(){
		if (this.value == this.defaultValue) {
		this.value = '';
		}
	}).bind('blur', function(){
		if (this.value == '') {
		this.value = this.defaultValue;
		}
	});

Note that this script uses jQuery so in order to work you’ll need to have jQuery installed.

To make all clear here is a demo.