Delete default value of an input text on click - javascript

I have an input text:
<input name="Email" type="text" id="Email" value="email#abc.example" />
I want to put a default value like "What's your programming question? be specific." in Stack Overflow, and when the user click on it the default value disapear.

For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email#abc.example" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see JQuery HTML5 placeholder fix « Kamikazemusic.com for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.

Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a JavaScript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the jQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email#abc.example" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email#abc.example';}"
onfocus="if (this.value == 'email#abc.example') {this.value = '';}" />

This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>

Using jQuery, you can do:
$("input:text").each(function ()
{
// store default value
var v = this.value;
$(this).blur(function ()
{
// if input is empty, reset value to default
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
// when input is focused, clear its contents
this.value = "";
});
});
And you could stuff all this into a custom plug-in, like so:
jQuery.fn.hideObtrusiveText = function ()
{
return this.each(function ()
{
var v = this.value;
$(this).blur(function ()
{
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
this.value = "";
});
});
};
Here's how you would use the plug-in:
$("input:text").hideObtrusiveText();
Advantages to using this code is:
Its unobtrusive and doesn't pollute the DOM
Code re-use: it works on multiple fields
It figures out the default value of inputs by itself
Non-jQuery approach:
function hideObtrusiveText(id)
{
var e = document.getElementById(id);
var v = e.value;
e.onfocus = function ()
{
e.value = "";
};
e.onblur = function ()
{
if (e.value.length == 0) e.value = v;
};
}

Enter the following
inside the tag, just add onFocus="value=''" so that your final code looks like this:
<input type="email" id="Email" onFocus="value=''">
This makes use of the javascript onFocus() event holder.

Just use a placeholder tag in your input instead of value

we can do it without using js in the following way using the "placeholder" attribute of HTML5
( the default text disappears when the user starts to type in, but not on just clicking )
<input type="email" id="email" placeholder="xyz#abc.example">
see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder

<input name="Email" type="text" id="Email" placeholder="enter your question" />
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
I think this will help.

Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP

Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email#abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>

I didn't see any really simple answers like this one, so maybe it will help someone out.
var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }

Here is an easy way.
#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});

Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>

Related

submitting the different value in jquery

I am having the below code to show input field with phone number in certain format. i.e., If phone number starts with 33,55 or 81 I will show it as (33) 1234-5678. If phone number starts with any other numbers, the format will be (123) 456-7890.
Now, the problem is when I submit the form, it is submitted as (33) 1234-5678. But I should submit 3312345678 and display (33) 1234-5678.
Could someone help me, how could i overcome this issue. I didnt use any jquery plugins;
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
You can change the value when the form is submitted, just before it is sent to the server:
$("form").on("submit", function(){
var originalVal = $("#criterion").val();
var newVal = originalVal.replace(/[^\d]/g, '');
$("#criterion").val(newVal);
});
You could have a hidden input that you store the original value of the input before modifying it.
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input type="hidden" id="org" name="org" />
-
$(document).ready(function() {
$("#criterion").change(function () {
var searchBy = $('#smartWirelessSearch').val();
$('#org').val($(this).val());
if(searchBy == 'Mobile'){
$(this).attr("criterion", $(this).val());
var twoDigit = $('#criterion').val().substr(0, 2);
var threeDigit = $('#criterion').val().substr(0, 3);
var remainingDigits = $('#criterion').val().substr(2, 10);
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
$('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
$('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
If you need to have the original cleaned value all the time, there are many ways to do that too. One simple solution is to have clean it by your self everytime input changes.
If so, replace $('#org').val($(this).val()); by $('#org').val($(this).val().replace(/[^\d]/g, ''));
This basically replaces everything that is not a digit with an empty string.
There are two possibilities to solve this, the first is to have a second (extra) hidden input like:
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15" maxlength="60" style="width:85%;" value="" placeholder="" onkeypress = "submitOnReturn(event);">
<input id="criterion_hidden" name= "criterion_real" type="hidden" size="15" maxlength="60" value="" placeholder="" onkeypress = "submitOnReturn(event);">
And populate it in your jquery:
jQuery(document).ready(function() {
jQuery("#criterion").change(function () {
var searchBy = jQuery('#smartWirelessSearch').val();
if(searchBy == 'Mobile'){
jQuery(this).attr("criterion", $(this).val());
var twoDigit = jQuery('#criterion').val().substr(0, 2);
var threeDigit = jQuery('#criterion').val().substr(0, 3);
var remainingDigits = jQuery('#criterion').val().substr(2, 10);
$("#criterion_hidden").val(twoDigit + remainingDigits); //update it here.
if (twoDigit == '33' || twoDigit == '55' || twoDigit == '81') {
jQuery('#criterion').val('('+twoDigit+')'+' '+remainingDigits.substr(0,4)+'-'+remainingDigits.substr(4,8));
} else {
jQuery('#criterion').val('('+threeDigit+')'+' '+remainingDigits.substr(1,3)+'-'+remainingDigits.substr(4,8));
}
}
});
});
The other solution is to change the value on the server side (PHP?) by using a replace with a regular expression such as /[^\d]/g.
On submit of the form replace input value of ( ) - with empty string "".
I would suggest two solutions:
1. Toggle Format
With this solution, you either show the formatted value in the input, or the clean digit-only value. So you would take care to show the digit-only value when the form is submitted, but also when the user edits the value (as suggested by #Rune FS):
jQuery(function($) {
function cleanMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Strip all non-digit characters
$("#criterion").val($("#criterion").val().replace(/[^\d]/g, ''));
}
}
function formatMobile() {
if ($('#smartWirelessSearch').val() == 'Mobile') {
// Apply format after first stripping all non-digit characters
$("#criterion").val($("#criterion").val()
.replace(/[^\d]/g, '')
.replace(/(33|55|81|...)(.*?)(....)$/, '($1) $2-$3'));
}
}
$("#myform").submit(cleanMobile);
$("#criterion").blur(formatMobile).focus(cleanMobile).keypress(function(e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
}
});
// Set initial format correctly on page load
formatMobile();
}, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<select id="smartWirelessSearch">
<option value="Mobile">Mobile</option>
</select>
<input id="criterion" name="criterion" type="tel" class="inputboxBg"
size="15" maxlength="60" style="width:85%;" value="" placeholder="">
<input type="submit" value="submit">
</form>
Run the snippet to see how it responds to focus and submit.
Note that the code above also:
Uses a regular expression to format the number;
attaches the keypress handler via code instead of the element's onkeypress attribute;
defines functions for the format manipulations so these can be referenced in blur, focus and submit events;
defines a dummy smartWirelessSearch element so the code is compatible with your form;
gave the form an id myform, which you should replace with yours.
2. Use Hidden Input
If you do not want the input value to visibly change at form submission, you could add a hidden input and give that the digit-only value, like this:
<input id="criterionClean" name="criterionClean" type="hidden">
<input id="criterion" name= "criterion" type="tel" class="inputboxBg" size="15"
maxlength="60" style="width:85%;" value="" placeholder=""
onkeypress="submitOnReturn(event);">
In your Javascript add one line:
if(searchBy == 'Mobile'){
// ... your code ...
// Then pass the digits only in the hidden input
$('#criterionClean').val($(this).val().replace(/[^\d]/g, ''));
}
Now you'll submit both the formatted and the cleaned value. Your server code could then use the clean digit-only value.
If you prefer the clean value to be called #criterion, then swap the names of the two inputs in html and in your code.

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

javascript clear field value input

I am making a simple form and i have this code to clear the initial value:
Javascript:
function clearField(input) {
input.value = "";
};
html:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);"/>
But what i don't want is that if the user fills the input but clicks it again, it gets erased. I want the field to have the starter value "Name" only if the input is empty. Thank you in advance!
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
update
here is a demo fiddle of the same
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[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();
Found here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
This may be what you want:
Working jsFiddle here
This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
var input= $(this);
input.innerHTML = '';
OP's question is no longer relevant- the question was asked in 2013 when the placeholder attribute wasn't well supported.
Nowadays you can just use <input placeholder="Your text here">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefplaceholder

Javascript change input type dynamically doesnt work on IE8

i have a input field for entering password in a webpage:
<input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" />
in the initial state the usershould read "password" as the initial value and when he starts typing a password, the field should change to type password. Also when he sets it back to blank or initial value the field should change type to "text" and show password.
I wrote code an got it working on Firefox, Chrome, and safari and its not changing the type to password on IE 8.
this is the js code i made by editing an existing function code:
function txtOnFocus2(elementId, defaultText)
{
if (document.getElementById(elementId).value == defaultText)
{
document.getElementById(elementId).value = "";
document.getElementById(elementId).type = "password";
}
}
function txtOnBlur2(elementId, defaultText)
{
var textValue = document.getElementById(elementId).value;
if (textValue == defaultText || textValue.length == 0)
{
document.getElementById(elementId).type = "text";
document.getElementById(elementId).value = defaultText;
}
}
This is working fine in Firefox,chrome and safari but doesn't change field type on IE 8.
An alternative solution would be to change your approach altogether. The following technique degrades gracefully, is more accessible, and less JavaScript-dependant:
HTML
<div><label for="email">Email</label> <input type="text" name="email" id="email" /></div>
<div><label for="password">Password</label> <input type="password" name="password" id="password" /></div>
JavaScript
$('input')
.focus(function() {
$(this).css('background-color', 'white');
})
.blur(function() {
if($.trim($(this).val()) == '') {
$(this).css('background-color', 'transparent').val('');
}
});
CSS
input {
background-color: transparent;
padding: 2px;
}
label {
color: gray;
padding: 2px 4px;
position: absolute;
z-index: -1;
}
Live demo: http://jsfiddle.net/rjkf4/
I tried that before. There is no way to do this in IE. This is an security thing. But still you can set the value of a password input in IE. So you can remove the text input and replace it with a password input and then set the value of new input.
function replaceInput(input){
var val = input.value,
passwordInput = document.createElement('input');
passwordInput.setAttribute('type', 'password');
passwordInput.value = val;
input.parentElement.appendChild(passwordInput);
input.parentElement.removeChild(input);
};
JSFIDDLE
Instead of:
foo.type = 'password';
try:
foo.setAttribute('type', 'password');
More info: http://www.javascriptkit.com/dhtmltutors/domattribute.shtml
In IE 6 and 7 (at least) you can't change the type of an input that's already in the document. You must create a new input, set its type, then replace the one that's in the document, e.g.
var el = document.createElement('input');
el.type = 'password'
var oEl = document.getElementById(elementId);
el.id = oEl.id;
// and so on for other properties that should be copied
oEl.parentNode.replaceChild(el, oEl);
Something ugly that however should work (I don't have IE8 handy to test it) would be placing your field in a div and replacing the whole thing with container.innerHTML = "<input ...>" when needed.
try this
http://www.electrictoolbox.com/jquery-toggle-between-password-text-field/
As an option you could just fake having a visible text in the password field by using a background image with that text on it.
$(".password").focus(function(){
$(this).css("background-image", 'url(regular_bg.png)')
})
$(".password").blur(function(){
if ($(this).val() == ""){
$(this).css("background-image", 'url(bg_with_password_label_on_it.png)')
}
})

JQuery Empty A Textfield When I click in it

How do I empty a textfield (html form) if I click in it to write something.
Pseudo Code:
On click #searchform
Erase String in #searchform
$('#searchform').click(function() { $(this).val('') })
Try it here
$('#searchform').click(function() {
if ($(this).val() == 'Enter search term') {
$(this).data('original', $(this).val()).val('');
}
});
$('#searchform').blur(function() {
if ($(this).val() == '') {
$(this).val($(this).data('original'));
}
});
EDIT As of now you should use the placeholder attribute and if you want, use the above as a polyfill for missing placeholder support.
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
And turn the original code into a plugin for easy use (with some small mods).
jQuery.fn.placeholder = function() {
return this.each(function() {
var value = $(this).attr('placeholder');
jQuery(this).val(value).addClass('placeholder');
jQuery(this).focus(function() {
if (jQuery(this).val() == value) {
jQuery(this).val('').removeClass('placeholder');
}
});
jQuery(this).blur(function() {
if (jQuery(this).val() == '') {
jQuery(this).val(value).addClass('placeholder');
}
});
});
};
I'd recommend you using the HTML5 placeholder attribute. For example:
<input type="text" placeholder="some default string if empty" />
This will work with most of the newest browsers and for older ones there is a workaround jQuery plugin. Here is the link to the placeholder plugin.
And then you simply call:
$('input[placeholder]').placeholder();
If you are wanting to clear a default value from a field such as "Enter Search Term" I use the following code:
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
and then on my input field I add:
onfocus="clearText(this)"
So it would be:
<input type="text" name="username" value="enter your name here" onfocus="clearText(this)">

Categories