JQuery Default text on empty text box - javascript

I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.
I have been trying a few things but nothing is working. Could someone please point me in the right direction?

Or you could just use the placeholder html5 attribute:
<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" />

it goes something like this
$('#yourElement').focus(function(){
//Check val for email
if($(this).val() == 'E-Mail'){
$(this).val('');
}
}).blur(function(){
//check for empty input
if($(this).val() == ''){
$(this).val('E-Mail');
}
});

you can use the placeholder attribute and then us this jquery as backup for IE
<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/>
$(document).ready(function () {
$('.watermark').focus(function () {
if ($(this).val() == $(this).attr('placeholder')) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
}
});
});

It's pretty straightforward. Just erase the value onfocus, and then (if the value is still empty) refill it onblur.

Call the below function and pass it two args: slightLabel(jQuery('#email_field'), 'email');
function slightLabel(input, text) {
jQuery(input).val(text);
jQuery(input).data('defaultText', text);
jQuery(input).focus(function(){
if(!jQuery(this).data('touched'))
{
jQuery(this).data('touched', true);
jQuery(input).val('');
}
});
// the part to restore the original text in
jQuery(input).blur(function(){
if(jQuery(this).val() == '')
{
jQuery(this).val(jQuery(this).data('defaultText'));
}
});
}

You could use one of the watermark plugins of jquery that do just that. I use a watermark plugin that has the following code
$.fn.watermark = function (c, t) {
var e = function (e) {
var i = $(this);
if (!i.val()) {
var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
i.replaceWith($c);
$c.focus(function () {
$c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
})
.change(function (e) {
i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
})
.closest('form').submit(function () {
$c.replaceWith(i);
});
}
};
return $(this).live('blur change', e).change();
};
Callable in jquery by setting the class of the input textbox to watermark like this
<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
title="Type keyword here" />
The title is what will be displayed in the watermark.

Use this Jquery-placeholder plugin
Using this plugin makes it possible to also use the placeholder attribute in non HTML5 capable browsers.

Related

Set an input field to accept only numbers with jQuery

I have to define an input text which accepts only integer numbers.
I tried with a regular expressions but the decimal part of the value is still visible.
I used this function:
$(document).on("input","input", function(e) {
this.value = this.value.replace(/[^\d\\-]/g,'');
})
How about this one?
$('input').on('input blur paste', function(){
$(this).val($(this).val().replace(/\D/g, ''))
})
<input>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Simple and easy to use. Try it:
edited: also call in onblur event to prevent paste.
function numOnly(selector){
selector.value = selector.value.replace(/[^0-9]/g,'');
}
<input type="text" onkeyup="numOnly(this)" onblur="numOnly(this)">
You can detect on keydown if is numeric and you can check on paste event if is numeric and remove all non-numeric. This remove dot too.
Original source : keydown detect : Paste remove
This code below has been modified from the original source.
Please try:
$( "#input" ).on("paste", function() {
setTimeout(function(){
if ($('#input').val() != $('#input').val().replace(/\D/g,""))
{
$('#input').val($('#input').val().replace(/\D/g,""));
}
},10)
});
$('#firstrow').on('keydown', '#input', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstrow">
<input id="input" type="text">
</div>
Finally I solved the above issue with my requirement to type only number is
$(document).on("input", ".skilltxt", function(e) {
this.value = this.value.replace(/[^\d]/g,'');
});
$(".skilltxt").on('paste',function(e) {
if(gBrowser=='IE') {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
}
else if((gBrowser=='Firefox')|| (gBrowser=='Chrome')){
var pastedData = (e.originalEvent || e).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, pastedData)
}
if(Math.floor(pastedData) == pastedData && $.isNumeric(pastedData)){
$(this).val($(this).val().replace(/[^\d]/g,''));
}
else{
return false;
}
});

JavaScript Input Focus Switching

I have the below code being used in a new web app of mine, though I can't seem to get it to work like it should.. I want to be able to load up the page, then if the client hits the "Tab" key then it will simply just focus to the other input field. There being only 2 input fields, this should be easy (at least I thought :P). Anyways, can anybody help me with this? Thanks in advance :)
var body = document.querySelector('body');
body.onkeydown = function (e) {
if ( !e.metaKey ) {
// e.preventDefault();
}
if (e.code == "Tab") {
console.log(e.code);
if ($('#username').is(":focus")) {
$('#password').focus();
} else if ($('#password').is(":focus")) {
$('#username').focus();
}
}
}
I'm assuming you're using JQuery since you use $ in your javascript so I wrote this example under that assumption. I'm assuming you want it to tab into the field regardless so if they press the tabkey, it defaults to the id="username" input element. I added in a preventDefault to stop the normal tab behavior. It seems that the tabs normal behavior is what causes it to not function properly. Hope I didn't misunderstand you and that this helps.
$("body").on("keydown", function(e) {
if (e.which !== 9 && e.keyCode !== 9) {
return;
}
console.log("Which Value:", e.which);
console.log("KeyCode Value:", e.keyCode)
e.preventDefault();
if (!$('#username').is(":focus")) {
$('#username').focus();
} else {
$('#password').focus();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="username">
<input id="password">
</body>
EDIT:
In case you wanted to do this without the JQuery selectors. Here's another example:
var body = document.getElementsByTagName("body");
body[0].onkeydown = function(e) {
var username = document.getElementById("username");
var password = document.getElementById("password");
if (e.which !== 9 && e.keyCode !== 9 && e.code !== "Tab") {
return;
}
e.preventDefault();
if (document.activeElement !== username) {
username.focus();
} else {
password.focus();
}
}
<body>
<input id="username">
<input id="password">
</body>
Simply, use autofocus to make default focus to UserID and use tabindex to move to password when user press Tab key.
UserId :<input type="text" name="fname" autofocus tabindex="1">
Password: <input type="text" name="fname2" tabindex="2">
You need e.PreventDefault() to stop the tab event from propagating and doing what it was going to do anyway. Only ignore event propagation for the tab key.
body.onkeydown = function (e) {
if (e.code == "Tab") {
console.log(e.code);
if ($('#username').is(":focus")) {
$('#password').focus();
} else if ($('#password').is(":focus")) {
$('#username').focus();
}
e.preventDefault();
}
}
Also consider setting type="password" on your password input.

Get the value of input text when enter key pressed

I am trying this:
<input type="text" placeholder="some text" class="search" onkeydown="search()"/>
<input type="text" placeholder="some text" class="search" onkeydown="search()"/>
with some javascript to check whether the enter key is pressed:
function search() {
if(event.keyCode == 13) {
alert("should get the innerHTML or text value here");
}
}
this works fine at the moment, but my question how to get the value inside the text field, I was thinking of passing a reference "this" to the function, or if they had id's then I could use ID's but then I don't see how I could differentiate between which one has been typed, bringing my back to the same problem again...
Try this:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
JS Code
function search(ele) {
if(event.key === 'Enter') {
alert(ele.value);
}
}
DEMO Link
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
jsFiddle example : http://jsfiddle.net/NH8K2/1/
Just using the event object
function search(e) {
e = e || window.event;
if(e.keyCode == 13) {
var elem = e.srcElement || e.target;
alert(elem.value);
}
}
Listen the change event.
document.querySelector("input")
.addEventListener('change', (e) => {
console.log(e.currentTarget.value);
});
You should not place Javascript code in your HTML, since you're giving those input a class ("search"), there is no reason to do this. A better solution would be to do something like this :
$( '.search' ).on( 'keydown', function ( evt ) {
if( evt.keyCode == 13 )
search( $( this ).val() );
} );
const $myInput = document.getElementById('myInput');
$myInput.onkeydown = function(event){
if(event.key === 'Enter') {
alert($myInput.value);
}
}
Something like this (not tested, but should work)
Pass this as parameter in Html:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
And alert the value of the parameter passed into the search function:
function search(e){
alert(e.value);
}

jQuery move cursor to end of text input

Currently I have an input box which has the value "Current Website"
When they click it I run this function:
function clearMeHttp(formfield) {
if (formfield.defaultValue == formfield.value) {
formfield.value = "http://";
}
};
It works fine if you click into the box, but if you tab into the box it just highlights the word "http://" which defeats the purpose of it unless they hit the right arrow key which I want to avoid.
Thanks!
Here's the other code: <input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">
restoreMe just fades default value back in gently with jquery
I have changed your code a bit, but uses jquery events instead of inline html.
Full script used:
var defaultVal = 'Current website';
$(function() {
$('.urlCheck').focus(function(e) {
if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
$(this).val('http://');
$(this).select(false);
}
});
$('.urlCheck').keyup(function(e) {
if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
$(this).val('http://');
}
});
$('.urlCheck').blur(function(e) {
$(this).val(defaultVal);
});
});
Working Link : http://jsfiddle.net/29gks/6/
The keyup event is the override for Chrome and Safari
You haven't use jquery so I follow you.
script:
function clearMeHttp(formfield) {
if (formfield.defaultValue == formfield.value) {
formfield.value="";
formfield.style.padding="0 0 0 40";
document.getElementById("http").style.display="block";
}
};
html:
<label id="http" style="float:left;position:absolute;display:none;">http://</label>
<input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">
That catch your requirement but may be not the way you want
You need to use setSelectionRange() (or selectionStart and selectionEnd) on most browsers and some TextRange shenanigans on IE < 9.
Here's my previous answer to the same question: How to place cursor at end of text in textarea when tabbed into

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