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
Related
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');
}
})
Pretty self-explanatory, I have a textarea and it's set to required, but it only prompts user if you actually click in the text area, if you submit without clicking inside the text area it will not prompt the alert.
Fiddle
<p class="textHeader">
<strong>
Which type of elements would you be in favor of for a future
pattern for interactive media to follow?
</strong>
<textarea
name="styled-textarea"
id="styled"
onfocus="this.value=''; setbg('#e5fff3');"
oninvalid="invalidComment(this);"
onblur="setbg('white')"
placeholder="Max characters 140"
maxlength="140"
required
>
</textarea>
</p>
Easy answer. You are already providing contents for textarea, some white space with how your existing HTML is laid out. Therefore a value has been provided. Make sure your textarea closing tag is right next to the opening tag, without any spaces, so there is no white space content in-between. Like this:
<p class="textHeader">
<strong>
Which type of elements would you be in favor of for a future
pattern for interactive media to follow?
</strong>
<textarea
name="styled-textarea"
id="styled"
onfocus="this.value=''; setbg('#e5fff3');"
oninvalid="invalidComment(this);"
onblur="setbg('white')"
placeholder="Max characters 140"
maxlength="140"
required
></textarea>
You can use a js library like abide
http://www.siegeengine.org/documentation/abide-html5-validation.html
Or if you prefere
<script type="text/javascript">
// without jQuery style
var bindEvents = function(event){
if( document.getElementById('styled').value.trim() === '' ){
event.preventDefault();
alert("Write something please");
}
};
window.onload = function(){
document.forms[0].addEventListener('submit', bindEvents, true);
};
// jQuery style
var bindEvents = function(){
$('form').on('submit', function(e){
if( $(this).val().trim() === '' ){
e.preventDefault();
alert("Write something please");
}
});
};
$(document).ready( bindEvents );
// i would not recommend this but it will work also
var initForm = function(){
document.getElementById('styled').focus();
document.getElementById('styled').blur();
}
window.onload = initForm;
</script>
I have been trying to ask this before, without any luck of explaining/proving a working example where the bug happens. So here is another try:
I’m trying to replicate a placeholder effect on a contenteditable DIV. The core concept is simple:
<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
$(this).empty();
});
</script>
This can sometomes work, but if the placeholder contains HTML, or if there some other processing being made, the editable DIV’s text caret is being removed, and the user must re-click the editable DIV to be able to start typing (even if it’s still in focus):
Example: http://jsfiddle.net/hHLXr/6/
I can’t use a focus trigger in the handler, since it will create an event loop. So I need a way to re-set the caret cursor in the editable DIV, or in some other way re-focus.
Here is a CSS only solution augmenting some of the other answers:-
<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
[contentEditable=true]:empty:not(:focus)::before{
content:attr(data-ph)
}
</style>
EDIT: Here is my snippet on codepen -> http://codepen.io/mrmoje/pen/lkLez
EDIT2: Be advised, this method doesn't work 100% for multi-line applications due to residual <br> elements being present in the div after performing a select-all-cut or select-all-delete on all lines. Credits:- #vsync
Backspace seems to work fine (at least on webkit/blink)
I've just published a plugin for this.
It uses a combination of CSS3 and JavaScript to show the placeholder without adding to the content of the div:
HTML:
<div contenteditable='true' data-placeholder='Enter some text'></div>
CSS:
div[data-placeholder]:not(:focus):not([data-div-placeholder-content]):before {
content: attr(data-placeholder);
float: left;
margin-left: 5px;
color: gray;
}
JS:
(function ($) {
$('div[data-placeholder]').on('keydown keypress input', function() {
if (this.textContent) {
this.dataset.divPlaceholderContent = 'true';
}
else {
delete(this.dataset.divPlaceholderContent);
}
});
})(jQuery);
And that's it.
You may need to manually update the selection. In IE, the focus event is too late, so I would suggest using the activate event instead. Here's some code that does the job in all major browsers, including IE <= 8 (which a CSS-only alternative will not):
Live demo: http://jsfiddle.net/hHLXr/12/
Code:
$('div').on('activate', function() {
$(this).empty();
var range, sel;
if ( (sel = document.selection) && document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(this);
range.select();
}
});
$('div').focus(function() {
if (this.hasChildNodes() && document.createRange && window.getSelection) {
$(this).empty();
var range = document.createRange();
range.selectNodeContents(this);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
});
just use css pseudo-classes.
span.spanclass:empty:before {content:"placeholder";}
I found that the best way to do this is to use the placeholder attribute like usual and add a few lines of CSS.
HTML
<div contenteditable placeholder="I am a placeholder"></div>
CSS
[contenteditable][placeholder]:empty:before {
content: attr(placeholder);
color: #bababa;
}
Note: the CSS :empty selector only works if there is literally nothing in-between the opening and closing tag. This includes new lines, tabs, empty space, etc.
Codepen
All you need is this little solution
[contenteditable=true]:empty:before{
content: attr(placeholder);
display: block; /* For Firefox */
}
Demo: http://codepen.io/flesler/pen/AEIFc
Here's my way:
It uses a combination of jQuery and CSS3. Works exactly like the html5 placeholder attribute!.
Hides itself right away when you input the first letter
Shows itself again when you delete what you input into it
HTML:
<div class="placeholder" contenteditable="true"></div>
CSS3:
.placeholder:after {
content: "Your placeholder"; /* this is where you assign the place holder */
position: absolute;
top: 10px;
color: #a9a9a9;
}
jQuery:
$('.placeholder').on('input', function(){
if ($(this).text().length > 0) {
$(this).removeClass('placeholder');
} else {
$(this).addClass('placeholder');
}
});
DEMO: http://jsfiddle.net/Tomer123/D78X7/
Here's the fix that I used.
<div contenteditable><em>Edit me</em></div>
<script>
$('div').focus(function() {
var target = $(this);
window.setTimeout(function() { target.empty(); }, 10);
});
</script>
I developed a jQuery plug-in for this. Take a look https://github.com/phitha/editableDiv
var curText = 'Edit me';
$('div').focusin(function() {
if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
$(this).empty();
}
}).focusout(function() {
if ($(this).text().toLowerCase() == curText.toLowerCase() || !$(this).text().length) {
$(this).html('<em>' + curText + '</em>');
}
});
This is not exact solution of your problem ..
in summernote options set
airMode:true
placeholder works in this way.
In .css
.holder:before {
content: attr(placeholder);
color: lightgray;
display: block;
position:absolute;
font-family: "Campton", sans-serif;
}
in js.
clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];
if(charCount){
this.charactorCount = charCount.innerText.length;
}
if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}
if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}
getContent(innerText){
this.clickedOnInput = false;
}
In .html
<div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>
this solution worked for me in angular project
I have a search field which basically gives the user a "tip" of what to search (which is the background image). I need to erase the background when he types something. But I'm not sure how.
This is the searchfield:
<input style="font-size:20px; width:300px; color: #444; background: url('http://chusmix.com/Imagenes/busca.png') white;" type="text" id="s" name="s" onblur="if(this.value == '') { this.style.background='url(http://chusmix.com/Imagenes/busca.png) no-repeat 0% 50% white';}">
Is there an easy way to do it? If you need more info please ask. Thanks
Add this little bit of javascript in the tag: onFocus='this.value=""';
I think you want to get rid of the onblur and instead make it onfocus (so the background changes when they enter the box).. or even onchange so whenever they type it goes away.
I am using Facebook like plugin from here
http://github.com/loopj/jQuery-Tokenizing-Autocomplete-Plugin
I just had a go at this one and it was really easy to implement using an asp.net page to output the JSON (from the search params) Then theres just a few lines of Javascript you need to create it (and the settings)
$(document).ready(function() {
$("#Users").tokenInput("../Services/Job/UnassignedUsers.aspx?p=<%= projectID %>&j=<%= jobID %>", {
hintText: "Begin typing the user name of the person you wish to assign.",
noResultsText: "No results",
searchingText: "Searching..."
});
});
Hope this might help you
Assume txtTopSearchBox is the id of text box and "Search" is the content on that (tip)
$(document).ready(function() {
$("#txtTopSearchBox").focus(function() {
$(this).removeClass().addClass("txtSearchBoxFocus").val("");
});
$("#txtTopSearchBox").blur(function() {
if (($(this).val() == "Search") || ($(this).val() == "")) {
$(this).removeClass().addClass("txtSearchBox").val("Search");
}
});
$("#txtTopSearchBox").keypress(function(e) {
if (e.which == 13) {
var key = $("#txtTopSearchBox").val();
key = escape(key);
window.location.href = "browse.aspx?search=" + key;
return false;
}
});
});
Tested and works in Fx 3.6, Safari 5 and Chrome. Image too big for field when not copying the attributes to the withoutTip too
<style type="text/css">
.withTip {
font-size:20px;
width:300px;
color: #444;
background: white url(http://chusmix.com/Imagenes/busca.png) }
.withoutTip { background: white url()}
</style>
<input class="withTip" type="text" id="s" name="s"
onkeyup="this.className=(this.value=='')?'withTip':'withoutTip'" />
or
<style type="text/css">
#s {font-size:20px; width:300px; color: #444;}
.withTip { background: white url(http://chusmix.com/Imagenes/busca.png) }
.withoutTip { background: white url()}
</style>
If you are interested in html5, the upcoming placeholder attribute will take care of this. But alas, not all browsers are html5 ready. The second sub-heading on this page shows browser compatibility.
Until then, the JavaScript method PMV describes works well.
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