I would like to insert a descriptive text inside an input element that disappers when the user click on it.
I know it is a very common trick, but I do not know how to do that..
What is the simplest/better solution?
If you're using HTML5, you can use the placeholder attribute.
<input type="text" name="user" placeholder="Username">
<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">
A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.
In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.
It's easy to implement and degrades nicely for screen readers and users with no javascript.
Take a look at the two examples here:
http://attardi.org/labels/
I usually use the second method (labels2) on my forms.
The common approach is to use the default value as a label, and then remove it when the field gains the focus.
I really dislike this approach as it has accessibility and usability implications.
Instead, I would start by using a standard element next to the field.
Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:
Relatively position a div that contains the input and label
Absolutely position the label
Absolutely position the input on top of the label
Remove the borders of the input and set its background-color to transparent
Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.
Whenever the input gains the focus, set that class.
The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).
This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.
I've put together solutions proposed by
#Cory Walker with the extensions from #Rafael
and the one form #Tex witch was a bit complicated for me
and came up with a solution that is hopefully
error-proof with javascript and CSS disabled.
It manipulates with the background-color of the form field to show/hide the label.
<head>
<style type="text/css">
<!--
input {position:relative;background:transparent;}
-->
</style>
<script>
function labelPosition() {
document.getElementById("name").style.position="absolute";
// label is moved behind the textfield using the script,
// so it doesnt apply when javascript disabled
}
</script>
</head>
<body onload="labelPosition()">
<form>
<label id="name">Your name</label>
<input type="text" onblur="if(this.value==''){this.style.background='transparent';}" onfocus="this.style.background='white'">
</form>
</body>
View the script in action: http://mattr.co.uk/work/form_label.html
<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">
Add an onblur event too.
When you start typing it will disappear.If empty it will appear again.
<%= f.text_field :user_email,:value=>"",:placeholder => "Eg:abc#gmail.com"%>
Simplest way...
Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers
http://jamesallardice.github.io/Placeholders.js/
One hint about HTML property placeholder and the tag textarea, please make sure there is no any space between <textarea> and </textarea>, otherwise the placeholder doesn't work, for example:
<textarea id="inputJSON" spellcheck="false" placeholder="JSON response string" style="flex: 1;"> </textarea>
This won't work, because there is a space between...
use this
style:
<style type="text/css">
.defaultLabel_on { color:#0F0; }
.defaultLabel_off { color:#CCC; }
</style>
html:
javascript:
function defaultLabelClean() {
inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].value == inputs[i].getAttribute("innerLabel")) {
inputs[i].value = '';
}
}
}
function defaultLabelAttachEvents(element, label) {
element.setAttribute("innerLabel", label);
element.onfocus = function(e) {
if (this.value==label) {
this.className = 'defaultLabel_on';
this.value = '';
}
}
element.onblur = function(e) {
if (this.value=='') {
this.className = 'defaultLabel_off';
this.value = element.getAttribute("innerLabel");
}
}
if (element.value=='') {
element.className = 'defaultLabel_off';
element.value = element.getAttribute("innerLabel");
}
}
defaultLabelAttachEvents(document.getElementById('MYID'), "MYLABEL");
Just remember to call defaultLabelClean() function before submit form.
good work
You do not need a Javascript code for that...
I think you mean the placeholder attribute. Here is the code:
<input type="text" placeholder="Your descriptive text goes here...">
The default text will be grey-ish and when clicked, it will dissapear!
I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here:
https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/
Here example with Label inside Input fields:
codepen.io/jdax/pen/mEBJNa
Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
<meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<style type="text/css" >
input.searcher
{
background-image: url(/images/search_back.png);
background-repeat: no-repeat;
background-attachment: scroll;
background-x-position: left;
background-y-position: center;
}
</style>
<script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
<input type="text" id="q" name="q" value="" />
<script type="text/javascript" language="JavaScript" >
// <![CDATA[
function f(e){
$('q').removeClassName('searcher');
}
function b(e){
if ( $F('q') == '' )
{
$('q').addClassName('searcher');
}
}
Event.observe( 'q', 'focus', f);
Event.observe( 'q', 'blur', b);
Event.observe( window, 'load', b);
// ]]>
</script>
</body>
</html>
Related
I was wondering how can i automatically make first character of the word in an input area
Currently my code is
Name:<input type='text' name='name' class='name' placeholder='Enter your name here'/>
You can try this: DEMO
Name:<input type='text' name='name' class='name' style="text-transform: capitalize;" placeholder='Enter your name here'/>
or add text-transform: capitalize; in your name in css.
The problem with using CSS (text-transform: capitalize) is that when the form gets submitted, the name will be submitted with a lowercase name.
The CSS works well for cosmetics but not for functionality.
You can use jQuery to force capitalization functionality in your input boxes:
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$('.name').keyup(function(event) {
var textBox = event.target;
var start = textBox.selectionStart;
var end = textBox.selectionEnd;
textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1).toLowerCase();
textBox.setSelectionRange(start, end);
});
});
</script>
Put this code between the <head> </head> on the page where your form is located.
Above jQuery will also force ALL CAPS to Capitalize.
Check out the Fiddle here: https://jsfiddle.net/cgaybba/6rps8hfo/
I think it should also be mentioned that if the form is on mobile, you can just use the autocapitalize attribute. see here for documentation
Try this
HTML CODE
<input type='text' name='name' class='name' placeholder='Enter your name here'/>
CSS CODE
<style>
.name
{
text-transform:capitalize;
}
</style>
Update you css
.name { text-transform: capitalize; }
The good side of using JS is that when the user submits the form, it retains the capitalized input values, but using css when the form is submitted, it looses the capitalized values (for frontend only).
Note for CSS: make sure you don't have any overriding styles else use !important.
//For CSS
input { text-transform: capitalize }
//For JS
$('.your-input').on('change keydown paste', function(e) {
if (this.value.length = 1) {}
var $this_val = $(this).val();
this_val = $this_val.toLowerCase().replace(/\b[a-z]/g, function(char) {
return char.toUpperCase();
});
$(this).val(this_val);
});
Just include → style="text-transform:capitalize;" inside your input tag.
I am using Dojo for tooltip. When, user move over the icon the message should be displayed.
.claro .dijitTooltipConnector {
background-image: none;
background-repeat: no-repeat;
border: 0 none;
height: 14px;
width: 16px;
z-index: 2;
}
I want this icon next to this DataTextBox. Who to do this? Please help
<td>
<p style="padding-left: 100px;">
<label id="acid">Date for CC:</label>
<input dojoType="dijit/form/DateTextBox" name="datecc" id="datecid" style="width:200px;" maxlength="50" />
</p>
</td>
Have you tried using dijit/Tooltip?
A simplified example from the documentation:
<button id="buttonId" data-dojo-type="dijit/form/Button">Button Text</button>
<div data-dojo-type="dijit/Tooltip" data-dojo-props="connectId:'buttonId',position:['above']">
Tooltip Content
</div>
So in your case you probably want a dijit/Tooltip whose connectId value refers to datecid and whose position value is ['left','right'] or whatever your position preferences are. (If it can't fit on the left, it'll go right as its second-choice.)
Note that this example uses HTML ID values, but other examples can show CSS selectors. (I've made a custom subclass that supports attach-point names, but it's still very experimental and hacky.)
Try using "dijit.showTooltip()" to show the tooltip at any place instantly, without need to write any HTML code for tooltips. (similarly, "dijit.hideTooltip" for hiding the same). Let me give a small example of how you can use it.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://dojotoolkit.org/reference-guide/1.9/_static/js/dijit/themes/claro/claro.css">
<script>dojoConfig = {parseOnLoad: true}</script>
<script src="http://dojotoolkit.org/reference-guide/1.9/_static/js/dojo/dojo.js"></script>
<script>
require(["dojo/parser", "dijit/form/ValidationTextBox", "dijit/form/DateTextBox", "dijit/Tooltip"]);
function showTooltip() {
var domNode = dijit.byId('datefld').domNode; //domNode to which the tooptip must point to
dijit.showTooltip("Enter your date of birth here!!", domNode,["above"]); // you can use "above" or "below" or "right" or "left"
}
function hideTooltip() {
var domNode = dijit.byId('datefld').domNode;
dijit.hideTooltip(domNode);
}
</script>
</head>
<body class="claro">
<label for="firstname">Name: </label>
<input type="text" name="firstname" data-dojo-type="dijit/form/ValidationTextBox" id="firstname" promptMessage="Enter your name here!"/><br/><br/>
<label for="firstname">DOB : </label>
<input type="text" name="datefld" data-dojo-type="dijit/form/DateTextBox" id="datefld" promptMessage="Enter your date of birth here!"/>
<br/><br/>
<span onmouseover="showTooltip()" onmouseout="hideTooltip()">hover here for tip!!</span>
</body>
</html>
Note: This is a bit legacy way of coding mixed with the new AMD design. But, this would be more elegant for your scenario.
I'm not a web guy, so this might be something really simple I'm missing, but:
Consider the following page:
http://pastehtml.com/view/1bg9qno.html
Which is basically a list of <input>s, and each input has a helper <span> with text (that will change along with the input's value on keyUp).
So when the list is long enough (like in the above HTML page), if you tab thru the inputs, you will eventually get to the input on the bottom of the page, tab again, and the browser will scroll down to the next input.
In my case, the input has the helper text which is crucial to my app.
The problem is that when the user tabs down to the input that is not visible, the browser only brings that input into the view, and not his entire parent (<div class="item">) which contains the helper text. As a result, this helper text is not visible to the user while he enters stuff in the input.
How can one tell the browser to bring the entire parent into view when focusing the out-of-view input?
Is there any elegant solution?
BTW: This doesn't happen in Chrome, since Chrome always scrolls down a part-page, but it always happens in Firefox which always scrolls as little as possible to the input.
The HTML looks like this:
<body>
<div class="item">
<input type="text" value="text" />
<br />
<span>helper text</span>
</div>
<hr />
...
<hr />
<div class="item">
<input type="text" value="text" />
<br />
<span>helper text</span>
</div>
</body>
<html>
<head>
<script>
function scrollParentIntoView(elem){
setTimeout(function(){
var children = elem.parentNode.children;
var lastChild = children[children.length - 1];
lastChild.scrollIntoView();
elem.parentNode.scrollIntoView();
//elem.ScrollIntoView();
},1);
}
</script>
</head>
<body>
...
<div>
<input onfocus="scrollParentIntoView(this);" />
...
<p>end</p>
</div>
...
</body>
</html>
I've tested on FF and Chrome and seems to do the job - you can see the input and 'end' when each '...' is replaced with a dozen tags
Here is a solution using jQuery. It's based on the height of your item container.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".item input").focus(function() {
var parent = $(this).parent();
// Check if the bottom of the item container is below the viewport
if ($(parent).position().top + $(parent).height() > $(window).scrollTop() + $(window).height())
{
// Adjust the scroll position according to the height of the item container
$(window).scrollTop($(window).scrollTop() + $(parent).height());
}
});
});
</script>
Edit
Here is a demo for you: http://pastehtml.com/view/1bnv1xb.html
This Javascript works in FF 3.6, IE 8, Safari 4, and Chrome 3.1. It doesn't require JQuery, doesn't need setTimeouts, and can be condensed to about 8 lines:
//Collect the elements
var ALL = document.getElementsByTagName("INPUT");
for(x=0;x<ALL.length;x++) {
//Add relative position style to allow offset math
ALL.style.position = 'relative';
ALL[x].onfocus = function() {
//Find scroll offset distance
var temp = this.offsetParent.offsetTop +
this.offsetParent.offsetHeight -
document.documentElement.clientHeight;
//Detect webkit browser and apply scroll offset as appropriate
window.devicePixelRatio ?
document.body.scrollTop = temp :
document.documentElement.scrollTop = temp;
}
}
Of course, the obvious solution here is to put all the important content above the input element, but it's obvious that that won't do for whatever reason, so here's another solution:
Remember that tabindex can be used to allow any element to be focused. This means that we can simply drop a tabindex on the parent of the input elements to allow the entire parent to gain focus and scroll into view.
However, this also means that tab must be tapped twice to get the input element focused. You will also need to explicitly set tabindex on the input element to have them be the next in line to gain focus.
<ol id="input">
<li tabindex="3">
<input type="text" tabindex="5" />
<p>Helper Text</p>
</li>
<li tabindex="7">
<input type="text" tabindex="10" />
<p>Helper Text</p>
</li>
</ol>
You'll also want to give the parent elements a :focus style instead of the rather ugly dotted outline.
See: http://www.jsfiddle.net/F2fwy/2
This works in Chrome and any other browser that supports placeholder text in HTML5
<input id="name" name="name" type="text" placeholder="Please enter your name..." required /> <br />
But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.
How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.
Safari and Chrome already support it (or the latest versions anyway).
Thanks.
One day I'll get around to properly documenting this, but see this example: http://dorward.me.uk/tmp/label-work/example.html
In short — position a <label> under a transparent <input> using <div> to provide background colour and borders.
Then use JS to determine if the label should be visible or not based on focusing.
Apply different styles when JS is not available to position the label beside the element instead.
Unlike using the value, this doesn't render the content inaccessible to devices which only display the focused content (e.g. screen readers), and also works for inputs of the password type.
I use this one: https://github.com/danbentley/placeholder
Lightweight and simple jQuery plugin.
Here is the simplest solution that I found working everywhere:
<input id="search"
name="search"
onblur="if (this.value == '') {this.value = 'PLACEHOLDER';}"
onfocus="if (this.value == 'PLACEHOLDER') {this.value = '';}"
/>
Replace PLACEHOLDER with your own.
At the moment, FF3 does not yet support the "placeholder" attribute of the "input" element. FF4, Opera11 and Chrome8 support it partially, i.e. they render the placeholder text in the field, but do not delete it when the user focuses in the field, which is worse that not supporting it at all.
I use the following snippet that I wrote with jQuery. Just add a class of textbox-auto-clear to any textbox on the page and you should be good to go.
<input type="text" value="Please enter your name" class="textbox-auto-clear" />
$(".textbox-auto-clear").each(function(){
var origValue = $(this).val(); // Store the original value
$(this).focus(function(){
if($(this).val() == origValue) {
$(this).val('');
}
});
$(this).blur(function(){
if($(this).val() == '') {
$(this).val(origValue);
}
});
});
I assume that you want to keep using the placeholder attribute for HTML5 browsers, in which case you'd have to do some browser detection and only apply the jQuery solution to browsers that don't support it.
Better yet, you can us the Modernizer library, as outlined in this answer.
Detecting support for specific HTML 5 features via jQuery
Here is a MooTools Plugin, that brings the placeholder to browsers that don't support it yet:
http://mootools.net/forge/p/form_placeholder
I use this one: https://github.com/Jayphen/placeholder
This lightweight and simple jQuery plugin is a fork of danbentley/placeholder.
Advantage: it adds a class "placeholder" to input fields that are temporarily filled.
Css ".placeholder {color:silver}" make the polyfill text look like a placeholder instead of regular input text.
Disadvantage: It doesn't polyfill the placeholder of a password field.
By the way...if anyone is interested...I found a nice elegant solution that is a jQuery plugin that is SOOO nice.
It literally is one line of jQuery, a minified js plugin, along with a simple class name on the input.
http://labs.thesedays.com/projects/jquery/clearfield/
It's the most beautiful thing I have discovered, next to 'Placeholder' in html.
The trick is to use javascript functions onBlur() and onFocus().
Here is the code that worked for me:
<script language="javascript" type="text/javascript" >
var hint_color = "grey", field_color = null;
var hinted = true;
function hint() { // set the default text
document.getElementById('mce-EMAIL').style.color = hint_color;
document.getElementById('mce-EMAIL').value = "<?php echo SUBSCRIPTION_HINT; ?>";
hinted = true;
}
function hintIfEmpty() { // set the default text, only if the field is empty
if (document.getElementById('mce-EMAIL').value == '') hint();
}
function removeHint() {
if (hinted) {
document.getElementById('mce-EMAIL').style.color = field_color;
document.getElementById('mce-EMAIL').value = "";
hinted = false;
}
}
function send() {
document.getElementById('subscription_form').submit();
hint();
}
</script>
<div style="position:absolute; display: block; top:10; left:10; ">
<form id="subscription_form" action="<?php echo SUBSCRIPTION_LINK; ?>" method="post" target="_blank">
<input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" style="width: 122px;" onBlur="hintIfEmpty();" onFocus="removeHint();" required>
<font style="position: relative; top:-1px;"><b>ok</b></font>
</form>
</div>
<script language="javascript" type="text/javascript" >
field_color = document.getElementById('mce-EMAIL').style.color;
hint();
</script>
SUBSCRIPTION_HINT (i.e.: "your e-mail" ) and SUBSCRIPTION_LINK (i.e.: the value of the 'action' tag in your EN mailchimp embed code...) are PHP constants used for localization.
For "placeholder" work in Firefox just add the attribute
::-moz-placeholder
in CSS tags.
Works for me, change your CSS to
::-webkit-input-placeholder {
color: #999;
}
In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.