Default text on input - javascript

How to set blank default text on input field and clear it when element is active.

In modern browsers, you may set the placeholder attribute on a field to set its default text.
<input type="text" placeholder="Type some text" id="myField" />
However, in older browsers, you may use JavaScript to capture the focus and blur events:
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
if (elem.addEventListener) elem.addEventListener(type, fn, false);
else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text
addEvent(textField, 'focus', function() {
if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
if (this.value === '') this.value = placeholder;
});
Demo: http://jsbin.com/utecu

Using the onFocus and onBlur events allows you to achieve this, I.e.:
onfocus="if(this.value=='EGTEXT')this.value=''"
and
onblur="if(this.value=='')this.value='EGTEXT'"
The full example is as follows:
<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />

Or simply
<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
This will not post back the default text once the box is cleared but also will allow the user to clear the box and see all results in the case of an autocomplete script.

Declare styles for inactive and active states:
.active {
color: black;
}
.inactive {
color: #909090;
}
Add the Javascript to handle the changing of state:
function toggleText(el)
{
var v = el.value;
//Remove text to allow editing
if(v=="Default text") {
el.value = "";
el.className = "active";
}
else {
//Remove whitespace
if(v.indexOf(" ")!=-1) {
split = v.split(" ").join("");
v = split;
}
//Change to inactive state
if(v=="") {
el.value = "Default text";
el.className = "inactive";
}
}
}
Add your input box, with the default value set, the inactive class set and Javascript handlers pointing to the toggleText() function (you could use event listeners to do this if you wish)
<input type="text" value="Default text" class="inactive" onFocus="toggleText(this);" onBlur="toggleText(this);">

From a usability point of view the text in the input component should be preserved only for user's input purposes. The possible default value in the input should be valid if left untouched by the user.
If the placeholder text is meant to be a hint for how to fill the input, it is better to be blaced near the input where it can be seen also when the input has been filled. Moreover, using a placeholder text inside text components can cause troubles e.g. with braille devices.
If a placeholder text is used, regardless of usability guidelines, one should make sure that it is done in an unobtrusive way so that it works with user agents without javascript or when js is turned off.

I have found jQuery plugin (http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/) and use it :)

What I did is put a placeholder attribute for modern browsers:
<input id='search' placeholder='Search' />
Then, I made a fallback for older browsers using JQuery:
var placeholder = $('search').attr('placeholder');
//Set the value
$('search').val(placeholder);
//On focus (when user clicks into the input)
$('search').focus(function() {
if ($(this).val() == placeholder)
$(this).val('');
});
//If they focus out of the box (tab or click out)
$('search').blur(function() {
if ($(this).val() == '')
$(this).val(placeholder);
});
This works for me.

You can use this plugin (I'm an co-author)
https://github.com/tanin47/jquery.default_text
It clones an input field and put it there.
It works on IE, Firefox, Chrome and even iPhone Safari, which has the famous focus problem.
This way you do not have to be worried about clearing input field before submitting.
OR
If you want to HTML5 only, you can just use attribute "placeholder" on input field

You can use placeholder attribute.
np. <input type="text" name="fname" placeholder="First name">
check http://www.w3schools.com/tags/att_input_placeholder.asp

Related

HTML Input - Undo history lost when setting input value programmatically

I have an HTML input. When a user types in it, I've set up the 'input' event to handle updating the input to a filtered version of what the user typed (as well as updating selectionStart and selectionEnd for smooth UX). This happens constantly in order to give the proper effect.
What I've noticed, however, is that whenever JS sets the value of an input via input.value = '...';, it appears the undo history for the input disappears. That is, pressing Ctrl-Z with it focused no longer steps back to the previous state.
Is there any way to either provide the input custom undo history, or otherwise prevent it from losing the history whilst still changing its value?
Here is a minimal example of my issue:
After typing in the top input (which rudimentarily adds periods between every character), Ctrl-Z does not undo.
<body>
<input type="text" id="textbox" placeholder="No undo"/><br/>
<input type="text" id="textbox2" placeholder="Undo"/>
<script>
var tbx = document.getElementById("textbox");
tbx.addEventListener('input', () => {
tbx.value = tbx.value + '.'
});
</script>
</body>
You can try storing the input's previous value in a variable, then listen for the Ctrl + Z key combination in a keydown event listener attached to the input. When it is fired, you can set the value of the input to the previous stored value.
btn.addEventListener('click', function() {
savePrevInput(input.value)
input.value = "Hello World!";
})
var prevInput;
function savePrevInput(input) {
prevInput = input;
}
input.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 90) {
if (prevInput) {
input.value = prevInput;
input.selectionStart = prevInput.length;
}
}
})
<input id="input" />
<button id="btn">Change</button>

Animated form, how to check input value on page refresh?

I have a form which uses dynamic styling. Consider this html
<div class="field-name field-form-item">
<label class="placeholder" for="name">Name</label>
<input class="form-input" id="name" type="text" name="name" maxlength="50" size="30">
</div>
The label is ABOVE the input, with CSS. When you click the label :
$('.placeholder').on('click focus', function() {
$(this).addClass('ph-activated');
$(this).siblings('input').focus();
})
Then the label is animated and let the user type in the input.
If the user dont wan't to write anything, the animation goes back, and hide input field :
$('input').on(' blur', function(){
if ($(this).val().length === 0) {
$(this).siblings('label').removeClass('ph-activated');
}
});
That's alright.
But when a user fill the input, THEN refresh the page and its browser didn't reset input fields(ie firefox) : the label is above the input, even if the latter is not empty.
I tried this :
$(document).ready(function() {
if ($('input').val().length) {
$(this).siblings('label').addClass('ph-activated');
}
})
But it doesn't seem to trigger, I tried several ways to write this function. Up to now I never managed to give the class ph-activated to a label with a filled input on page refresh.
Sorry I can't fiddle this. I just have far too much html/css/js/php to copy paste
Well you are targeting wrong element in $(document).ready because you are referring label with this thinking that $(this) is input whereas it is document. So try applying below code and I hope there will be multiple input elements in page, so I've used $.each and looping through all the inputs
$(document).ready(function() {
$('input').each(function(){ //loop through each inputs
if ($(this).val().length) {
$(this).siblings('label').addClass('ph-activated');
}
});
})
DEMO - Inspect the label and you will find ph-activated class added to label
Try this one:
$(document).ready(function() {
var length = $('input').filter(function( index ) {
return ($(this).val() !== '');
}).length;
if (length > 0) {
$(this).siblings('label').addClass('ph-activated');
}
})

How to change <input type="file"> design so it won't display the text-field? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
input type=file show only button
The has this kind of design:
Can I modify it so it won't show the text field?
a very good guide is found in quirksmode - Styling an input type="file"
quote with some modifications to match question:
Take a normal <input type="file"> and put it in an element with position: relative. or absolute
To this same parent element, add an image or a button, which have the correct styles. Position this element absolutely, so
that they occupy the same place as the <input type="file">.
Set the z-index of the <input type="file"> to 2 so that it lies on top of the styled image or button.
Finally, set the opacity of the <input type="file"> to 0. The <input type="file"> now becomes effectively invisible, and the styled
image or button shines through, but you can still click on the "Browse"
button. (Note that you can't use visibility: hidden, because a truly
invisible element is unclickable, too, and we need the <input
type="file"> to remain clickable)
Suggestion: You can use the uploadify plugin.
Don't see a jQuery tag in your question but hey, it's helpful, and possibly quite easy to rewrite in vanilla JS. This is a little jQuery plugin I extracted from Ideal Forms, a plugin I maintain at github. It covers all the basics to do what you want, with fallback for IE and multiple for HTML5 browsers. Plus handling events and markup replacement. CSS is on your own, but nothing too complicated to style as you can see. You can hide the text field too if you want. The idea here is that this allows for ANY customization possible with CSS.
$.fn.toCustomFile = function () {
return this.each(function () {
var
$file = $(this), // The file input
// Necessary markup
$wrap = $('<div class="wrap">'),
$input = $('<input type="text" class="filename" />'),
$button = $('<button type="button" class="upload">Open</button>')
// Hide by shifting to the left, that way can
// still use events that are otherwise problematic
// if the field is hidden as in "display: none"
$file.css({
position: 'absolute',
left: '-9999px'
})
// Events
$button
.attr('tabIndex', -1) // disable focus on button for better usability
.click(function () {
$file.trigger('click') // Yes, `click`, not `change`. Crossbrowser compat.
})
$file
.attr('tabIndex', -1)
.on({
change: function () {
// Detect if browser supports HTML5 "file multiple"
var multipleSupport = typeof $('input')[0].multiple !== 'undefined',
files = [],
fileArr,
filename
if (multipleSupport) {
fileArr = $file[0].files
for (var i = 0, len = fileArr.length; i < len; i++)
files.push(fileArr[i].name)
filename = files.join(', ')
} else {
filename = $file.val().split('\\').pop() // Remove fakepath
}
$input.val(filename)
// Set filename as title tooltip on
// input field for better usability
$input.attr('title', filename)
},
focus: function () {
$input.trigger('focus')
}
})
$input
.on({
keyup: function () { $file.trigger('change') },
focus: function () { $file.trigger('change') },
blur: function () { $file.trigger('blur') },
// Open files when pressing [ENTER]
// on the input field
keydown: function (e) { if (e.which === 13) $file.trigger('click') }
})
// Append to DOM
$wrap.append($button, $input).insertAfter($file)
})
}
Here's a gist for ease of use: https://gist.github.com/3051209

using jquery to change contents of form upon typing

I am trying to get the default value to not go away on click, but rather when the user starts typing (so they know what the field is for)....the problem is the following:
when I use onchange instead of onfocus it keeps the default value in there when they start typing. If its confusing what I am doing go to facebook and look how their search box works...thats what I am going for.
<script>
function uFocus() {
$('#fakeusername').hide();
$('#username').show();
$('#username').focus();
}
function uBlur() {
if ($('#username').attr('value') == '') {
$('#username').hide();
$('#fakeusername').show();
}
}
</script>
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text' name='fakeusername' id='fakeusername' value=' Username' onfocus='uFocus()' />
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' />
Two options:
In HTML5, the placeholder attribute will simulate what you want with no Javascript needed.
<input type='text' name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' />
The second, and I believe the approach used by Facebook, is to swap a background image containing the sample text with a blank one. So you might create two background images (the first containing the words "Type your username" in the font used by the input, the second a blank) and set them to flip whenever the input is focused.
Is this what you are looking for:
$("#fakeusername").on({
focus: function() {
$(this).css('color', '#000');
},
blur: function() {
$(this).css('color', 'grey');
},
keydown: function() {
if ($(this).val()==' Username') {
$(this).val('');
}
}
});
FIDDLE
Here's a method that places label over top of input and requires proper for/ID match to allow browser to do default focus of input when clicking on label. Positions label over top of input, if no value of input on blur will show label again. Using label makes it accessible
http://jsfiddle.net/UCxaZ/2

How can I position a label inside its textfield?

I have many textfields that show instruction text within the textbox (how the default value would look). On focus the color of the text becomes lighter, but doesn't go away until text is entered. When text is erased, the label returns. It's pretty slick. A default value doesn't cut it, because these go away onfocus.
I have it working, but the code is complicated because it relies on negative margins that correspond to the individual widths of the textfields. I want a dynamic solution where the label for its textfield is positioned correctly automatically, probably using a script.
Any help would be greatly appreciated. But I am not looking for default values as a solution.
Thanks.
Mike
Edited to be more precise.
Edited again to provide some simple code that illustrates the effect I am after:
<input style="position: relative; width: 150px; font-size: 10px; font-family: Verdana, sans-serif; " type="text" name="name" id="name"
onfocus="javascript: document.getElementById('nameLabel').style.color='#BEBEBE';"
onkeypress="javascript: if (event.keyCode!=9) {document.getElementById('nameLabel').innerHTML=' ';}"
onkeyup="javascript: if (this.value=='') document.getElementById('nameLabel').innerHTML='Your Name';"
onblur="javascript: if (this.value=='') {document.getElementById('nameLabel').style.color='#7e7e7e'; document.getElementById('nameLabel').innerHTML='Your Name';}"/>
<label id="nameLabel" for="name" style="position: relative; margin-left: -150px; font-size: 10px; font-family: Verdana, sans-serif;">Your Name</label>
I would have taken a different approach (It's not entirely my idea, but i can't find the source for credit):
1st - Use html5 "placeholder" property.
2nd - Use Modernizr.js to detect support of placeholders in the browser and a simple jQuery script to add support to browsers that doesn't support it.
So, the html will look something like that:
<input type="text" class="placeholder" placeholder="Help Text" />
<textarea class="placeholder" placeholder="Another help text"></textarea>
The css:
.placeholder{color:#ccc;}
And the javascript:
/* Set placeholder for browsers that don't support HTML5 <input placeholder='text'>
* Depends on Modernizr v1.5
*/
if (!Modernizr.input.placeholder){
$('input[placeholder], textarea[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.addClass('placeholder');
input.val(input.attr('placeholder'));
}
})
//Run once on load
.blur();
// Clear all 'placeholders' on submit
$('input[placeholder], textarea[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
});
}
What you are asking here is probably what is called textbox watermark.
For this, you usually don't use a label (control) inside a textfield. Instead you replace the content of the textfield when the real content of the text field is empty with some text using certain CSS property and then remove it once you blur out (w/ additional check to see if the text inside the textbox itself is the same as the watermark text. If it is, blank the field again.)
Try this. It's pretty simple implementation of this using jquery and css.
Here's one that I borrowed from somewhere:
$(function() {
// Give the textbox a watermark
swapValues = [];
$('.your_input_class').each(function(i){
$(this).val("Please enter xyz");
swapValues[i] = $(this).val();
$(this).focus(function(){
if ($(this).val() == swapValues[i]) {
$(this).val("").css("color", "#333");
}
}).blur(function(){
if ($.trim($(this).val()) == "") {
$(this).val(swapValues[i]).css("color", "#ccc");
}
});
});
});
And then for your input box:
<input class="your_input_class" type="text" value="" />
It remembers the value that is stored in it when the page loads (well, I'm setting mine directly in the JS) and it also changes the color when it's focused/not focused.
Do you mean like this? But instead of 'required' it would have the label?
I used a jQuery solution where I set the value of the input to 'required'. The input has a class of gray so the default text is lighter.
Edit after comment
Instead of using focus, you can change the input values on keydown and keyup.
$('.required_input').keydown(function()
{
if (this.value == 'required')
{
$(this).val('').removeClass('gray');
}
} );
$('.required_input').keyup(function()
{
if (this.value == '')
{
$(this).val('required').addClass('gray');
}
} );
$('.required_input').blur(function()
{
if (this.value == '')
{
$(this).val('required').addClass('gray');
}
} );
<script type="text/javascript">
window.onload = function(){
inputs = document.getElementsByTagName("input");
for(i = 0; i < inputs.length;i++){
var feild = inputs[i];
if(feild.type == "text"){
var label = document.getElementById(feild.id + "Label");
label.style.left = "-" + feild.clientWidth;
}
}
}
</script>
This bit of script should do what you wanted

Categories

Resources