Form input show hide default value on focus - javascript

I am using the below code to show hide the default input value on focus. However, I am going to be using a few forms on one page and dont really want to have create this js for each input field, pretty time consuming and probably a bit too much js.
Html
<input type="text" class="sb" value="Search CT..."/>
Javascript
//search box
$("input.sb").focus(function(){
if ( $(this).val() == "Search CT...")
$(this).val('');
});
$("input.sb").blur(function(){
if ( $(this).val() == "")
$(this).val('Search CT...');
});
I was wondering if there was a way to create some generic JS to show/hide the default value, regardless of its content which would work on all form inputs??
Hope this makes sense, thanks very much.

This code will look through all your text input elements and textarea elements on page load. It will store their original values using $.data. It will then do the emptying and refilling as appropriate.
$(document).ready(function(){
$('form input:text, form textarea').each(function(){
$.data(this, 'default', this.value);
}).focus(function(){
if ($.data(this, 'default') == this.value) {
this.value = '';
}
}).blur(function(){
if (this.value == '') {
this.value = $.data(this, 'default');
}
});
});

Try below code -
$(document).ready(function(){
var value = '';
$("input.sb").focus(function(){
value = $(this).val();
if (value != ""){
$(this).val('');
}
});
$("input.sb").blur(function(){
if ( $(this).val() == ""){
$(this).val(value);
}
});
});

Looks like you're using jQuery. Have you tried using a plugin?
Here's one that will do what you need:
http://plugins.jquery.com/content/default-text-inputtext-fields-required-rule-modification

You could create a map, more or less like this:
Javascript
function setEvents( id, txt ){
$("#" + id)
.focus(function(){
if ( $(this).val() == txt) $(this).val('');
})
.blur(function(){
if ( $(this).val() == "") $(this).val(txt);
});
}
var map = {
input1: "your text",
input2: "other text"
};
for(var i in map){
setEvents( i, map[i] );
}
Where the keys of the map object represent input ID's and the values represent the default value

$("input").focus(function(){
$(this).val('');
});
or give a common class for each input field

Related

Can I hide the text box value if the value is 0?

Please help I am able to do all the calculations I need as long as I make certain text boxes default value 0 but I do not want these boxes to show a 0 if nothing is put in them. Can I hide the text box if the value is 0? there are servral text boxs in the sheet.
Edit:
Op wants also to validate form ,no submit() if values are not numbers or are empty.
Here's a Fiddle
$(function() {
$('input[type="text"]').each(function() {
var value = $(this).val();
if(value == 0) {
$(this).val('');
}
});
});
Answer to your comment about validation of form if input's value is not number or is empty :DEMO HERE
$(document).ready(function() {
$('input[type="submit"]').click(function(e){
var isEmpty=false;
e.preventDefault();
$('input[type="text"]').each(function() {
if($(this).val() ==0||$(this).val() =='' || isNaN($(this).val())) {
$(this).val('');
isEmpty=true;
}
});
if(isEmpty) {
alert('please fill all values');
return false;
}
else $('form').submit();
});
});
First Answer :This solves your issue : JSFIDDLE DEMO HERE
$(document).ready(function()
{
$('input[type="text"]').each(function()
{
if($(this).val() == 0) $(this).val('');
});
});

Javascript condition input id statement

ihave this code working perfectly, to simulate a prefill input field with an image :
<script>
$('#example).focus(function(){
var newValue = $(this).val();
if ($(this).val() == ""){
$(this).css("background-image", "none");
}else{
$(this).val(newValue);
}
}).blur(function(){
var newValue = $(this).val();
if ($(this).val() == ""){
$(this).css("background-image", "url(assets/templates/herveou-coiffure/css/pre_input.png)");
}else{
$(this).val(newValue);
}
});
</script>
The thing i need to use this with few input field (at least 2) so i tried something like this :
<script>
$('#example, example2').focus(function(){
var newValue = $(this).val();
if ($(this).val() == ""){
$(this).css("background-image", "none");
}else{
$(this).val(newValue);
}
}).blur(function(){
var newValue = $(this).val();
if ($(this).val() == ""){
if ($('#example2')[0]){
// Do something here if an element with this class exists
$(this).css("background-image", "url(assets/templates/herveou-coiffure/css/headers.jpg)");}
if ($('#example')[0]){
// Do something here if an element with this class exists
$(this).css("background-image", "url(assets/templates/herveou-coiffure/css/pre_input.png)");}
}else{
$(this).val(newValue);
}
});
</script>
Of course i'm not a javascritp expert and it does not work, anyone can help ??
Thank you very much...
Each time you are selecting an ID, you need to remember to use the ID selector #.
You need to use $('#example, #example2') instead of $('#example, example2').
When you write $('<selector1>, <selector2> , ....'. You should write the appropriate selector in each parameter. So You should change $('#example, example2') to be $('#example, #example2').

How to target all input text and password value?

I'm trying to figure out how to target every input(text and password) field on all forms on the page document to remove the default value when on focus with this single script:
$(document).ready(function()
{
Input = $('input');
default_value = Input.val();
$('input').focus(function()
{
if($(this).val() == default_value)
{
$(this).val("");
}
}).blur(function()
{
if($(this).val().length == 0)
{
$(this).val(default_value);
}
});
});
It works only on the first input text element in the first form on my page, but nothing on the rest. Please help!
Get all the input type text value:
$("input:text").each(function() {
alert($(this).val());
});
Get all input type password value:
$("input:password").each(function() {
alert($(this).val());
});
That's because val only returns the value of the first selected element, instead of storing the values, you can use defaultValue property of the HTMLInputElement object.
$('input[type=text], input[type=password]').focus(function() {
if (this.value === this.defaultValue) $(this).val("");
}).blur(function(){
if (this.value.length === 0) this.value = this.defaultValue;
});
http://jsfiddle.net/MscgZ/

CKEditor on focus remove default value

For a normal input field i can write something like the below code, which will remove the default value of an input field when i click, and if i dont write anything in the input field, than the default value will return when i leave the input field.
jQuery('input[type="text"]').focus(function()
{
if (this.value == this.defaultValue)
{
this.value = '';
}
if(this.value != this.defaultValue)
{
this.select();
}
});
jQuery('input[type="text"]').blur(function()
{
if (this.value == '')
{
this.value = this.defaultValue;
}
});
But i have no clue how to do this with CKEditor.. Can I get some help.
I found this code which will alert when I click in the CKEditor. But I dont know how modify it to work the way I need.
CKEDITOR.instances['post_content'].on('focus', function()
{
alert(1);
});
Have you tried this?
CKEDITOR.instances['post_content'].on('focus', function()
{
if (this.value == defaultValue)
{
this.value = '';
}
});
Combining the idea above with [this other SO article][1]:
// delete default text on focus
CKEDITOR.instances['editor1'].on('focus', function () {
var defaultText = '<p class=\"ckNormal\">Type your comment here</p>';
var currentText = CKEDITOR.instances.editor1.getData();
// debug - removed
// alert(defaultText + '\n' + currentText);
if (defaultText.trim()==currentText.trim()) {
CKEDITOR.instances.editor1.setData('');
}
});
You probably won't need to trim the text before testing. This uses getData to find what the text is, and setData to change it.

Showing Placeholder text for password field in IE

I know there is a ton of placeholder questions, but I am trying to perfect mine.
My current code works great and does what it's supposed to. The problem is, when I go to place the "password" placeholder, it puts the placeholder in the masking characters. Any ideas on how to get around that?
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
var active = document.activeElement;
$(':password').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':password').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
My field for the pass:
<div id="loginform_pass"><input class="login" tabindex="2" type="password" placeholder="Password" name="password" maxlength="30"></div>
You could also try this... it detects that the browser does not have support for placeholder and works for all input types
function FauxPlaceholder() {
if(!ElementSupportAttribute('input','placeholder')) {
$("input[placeholder]").each(function() {
var $input = $(this);
$input.after('<input id="'+$input.attr('id')+'-faux" style="display:none;" type="text" value="' + $input.attr('placeholder') + '" />');
var $faux = $('#'+$input.attr('id')+'-faux');
$faux.show().attr('class', $input.attr('class')).attr('style', $input.attr('style'));
$input.hide();
$faux.focus(function() {
$faux.hide();
$input.show().focus();
});
$input.blur(function() {
if($input.val() === '') {
$input.hide();
$faux.show();
}
});
});
}
}
function ElementSupportAttribute(elm, attr) {
var test = document.createElement(elm);
return attr in test;
}
Could you just swap out the original text field with a password field?
$('#pass').focus(
function(){
var pass = $('<input id="pass" type="password">');
$(this).replaceWith(pass);
pass.focus();
}
);
<input id="pass" type="text" value="Passowrd">
http://jsfiddle.net/UrNFV/
I ran into this problem with IE before. Here's my solution :)
http://jsfiddle.net/mNchn/
If I'm understanding this right, you want the field to say "Password" when nothing has been typed into it; however, "Password" gets displayed as "********".
A decent fix to that (which also degrades gracefully, depending on how you code it) is to:
Put a LABEL before the password INPUT. Set the LABEL's text to "Password", and set its for attribute to point to the INPUT's ID, so that the INPUT is focused when the LABEL is clicked.
Use CSS to position the LABEL on top of the INPUT, so that they overlap, and it looks like "Password" is inside of the INPUT.
Make it so that the LABEL is only visible when some CSS class (.showMe, for example) is applied to it.
Use JavaScript to hide the LABEL
...if the INPUT's value is an empty string
...or if the user has selected (focused) the INPUT.
Depending on whether or not you want to be able to dynamically change the text inside the placeholder, your simplest solution might be to have the placeholder text be an image.
input {
background: url(_img/placeholder.png) 50% 5px no-repeat;
.
.
.
}
input:focus {
background: none;
}
Clearly there are many different ways of using this method, and you will have to use some kind of a fix to get :focus to work on the browsers that don't support it.
Here my plugin :
if(jQuery.support.placeholder==false){
// No default treatment
$('[placeholder]').focus(function(){
if($(this).val()==$(this).attr('placeholder'))
$(this).val('');
if($(this).data('type')=='password')
$(this).get(0).type='password';
});
$('[placeholder]').blur(function(){
if($(this).val()==''){
if($(this).attr('type')=='password'){
$(this).data('type','password').get(0).type='text';
}
$(this).val($(this).attr('placeholder'));
}
}).blur();
}
I had the same problem so i wrote a little plugin
$.fn.passLabel = function(){
var
T = $(this),
P = T.find('input[type=password]'),
V = pass.val();
P.attr('type','text');
P.focus(function(){
if(V == "")
P.attr('type','password');
});
}
now you just call it for the from at it will find all input fields with the password
attribute.
eg.
$('form').passLabel();
A bit late however same here, i was working on the issue too IE9 doesnot show the password placeholder as text, in almost all the answers on the internet some suggest changing the type some but if u do this u will have another issue on the login page like when you will see with double click on password field as its type changed to text from password, btw it works with prop. e.g. prop("type","password") if you want to change the type of an element.
on the other hand i think most answers come from a single solution its like focus and blur actions of elements. but when u apply this plugin other text fields will also be effected there is no specific or i can say generlized solution, i have still a minor issue on the login page with the password field but its showing the text correctly. anyway. here is how i have configured, copied,changed and/or another inherited anwers here.
(function($) {
$.fn.placeholder = function() {
$('input[placeholder], textarea[placeholder]').focus(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
if (input.prop("id") === "password") {
input.prop("type", "password");
}
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() === '' || input.val() === input.attr('placeholder')) {
input.addClass('placeholder');
if (input.prop("type") === "password") {
input.prop("type", "text");
}
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('input[placeholder], textarea[placeholder]').each(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
}
});
});
};
})(jQuery);
still an active prolem ... :D

Categories

Resources