Please do not give a negative vote if I am wrong with asking this question. I have a TextBox like this:
<input class="login-inpt" runat="server" name="loginName" type="text" value="User Name" />
It currently holds a default value. I want the default value to be cleared and replaced with a cursor when I click on the TextBox.
For newer browsers (IE>9):
<input type="text" id="userName" placeholder="User Name" />
For older:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Placeholder support</title>
</head>
<body>
<input type="text" id="userName" placeholder="User Name" />
<script src="../js/vendor/jquery-1.10.2.min.js"></script>
<script src="../js/vendor/jquery-migrate-1.2.1.js"></script>
<script src="../js/vendor/modernizr-latest.js"></script>
<script src="../js/placeholder.js"></script>
</body>
</html>
placeholder.js (jQuery, Modernizr)
var Placeholder = (function ($, document) {
/* Static Content */
var _$document = $(document);
/* Events */
var _initPlaceholders = function () {
_$document.find('input:text').each(function () {
var $this = $(this);
$this.css({ color: '#888' }).val($this.attr('placeholder'));
});
};
var _placeholderEvent = function () {
var $input = $(this), placeholderValue = $input.attr('placeholder');
if ($input.val() === placeholderValue) {
$input.css({ color: '#000' }).val('');
return;
}
if ($input.val() === '') {
$input.css({ color: '#888' }).val(placeholderValue);
}
};
var _bindEvents = function () {
if (!Modernizr.input.placeholder) {
_initPlaceholders();
_$document.on('focus blur', 'input:text', _placeholderEvent);
}
};
var init = function () {
_bindEvents();
};
return {
init: init
};
})(jQuery, document);
Placeholder.init();
You can try this
<input type="text" value="user name" onfocus="if(this.value=='user name') this.value='';">
HTML:
<input type="text" value="user name" id="userName" />
With jQuery:
$(function() {
$('#userName').click(function() {
$(this).val('').unbind('click');
});
});
EDIT: Here's a demo
add the following as an attribute to your input tag:
onfocus="if(this.value=='A new value') this.value='';"
From: How to clear a textbox using javascript
I got the solution Thanks.
input type="text" id="userName" onfocus="inputFocus(this)" onblur="inputBlur(this)"
function inputFocus(i) { if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; } } function inputBlur(i) { if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; } }
You already got good answers but if you are newbie it might interest you how it could work without libraries.
Here is HTML:
<input id="textBox" class="textBox phrase" type="text" value="Enter Your Text..">
you don't need to set class and id you could pick one of them
Here is JavaScript:
var textBox = document.getElementById('textBox'), //probably the fastest method
/**************************additionally possible****************************
var textBox = document.getElementsByTagName('input')[0], //returns HTMLInputElement list (since we've got only one we chose the first one)
or
var textBox = document.querySelectorAll('textBox'), //works almost the same way as jquery does except you don't get all jquerys functionality
or
var textBox = document.getElementsByClassName('textBox')[0], //i guess its a least supported method from the list
***************************************************************************/
//text you want to choose for you input
phrase = "Enter Your Text..";
function addEvent(el, ev, fn) {
//checking method support
//almost every browser except for ie
if(window.addEventListener) {
el.addEventListener(ev, fn, false);
}
//ie
else if(window.attachEvent) {
el.attachEvent('on' + ev, fn);
el.dettachEvent('on' + ev, fn);
}
}
addEvent(textBox, 'focus', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if the text in your text box is your phrase then clean it else leave it untouched
target.value = target.value === phrase ? "" : target.value;
});
addEvent(textBox, 'blur', function (){
//cross browser event object
var e = e || window.event,
target = e.target;
//if your text box is not empty then leave it else put your phrase in
target.value = target.value ? target.value : phrase;
});
$('.login-inpt').focus(function() {
$(this).val('');
});
$('.login-inpt').focusout(function() {
$(this).val('User Name');
});
check out here http://jsfiddle.net/TDUKN/
Related
I have a phone mask 9999-9999. But, I want it to be 99999-9999 if the user inputs another number. It is working, but the input happens in the penultimate place instead of the last one. Here is an example:
input: 123456789
expected result: 12345-6789
actual result: 12345-6798
I tried .focus() but it only works when debugging. I think it is something related to it having time to execute since the code is stopped, but i'm not sure.
$(document).ready(function () {
$('#TelContato').unmask();
$('#TelContato').prop('placeholder', '9999-9999');
$('#TelContato').mask('0000-0000');
mask2 = false;
var masks = ['0000-0000', '00000-0000'];
$("#TelContato").keypress(function(e){
var value = $('#TelContato').val().replace(/-/g, '').replace(/_/g, '');
//changes mask
if (value.length == 8 && mask2 == false) {
$('#TelContato').unmask(masks[0]);
$('#TelContato').mask(masks[1]);
mask2 = true;
}
})
//this is a keyup method because detects backspace/delete
$("#TelContato").keyup(function (e) {
var value = $('#TelContato').val().replace(/-/g,'').replace(/_/g, '');
//changes mask back
if (value.length <= 8 && mask2 == true) {
$('#TelContato').unmask(masks[1]);
$('#TelContato').mask(masks[0]);
mask2 = false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
It seems your problem is that you are unmasking, right before masking. You do not need to unmask, just updating mask (reconfiguring) should work.
$(document).ready(function() {
const masks = ['0000-0000', '00000-0000'];
const maskedElem = $('#TelContato');
maskedElem.prop('placeholder', '9999-9999');
maskedElem.mask(masks[0]);
maskedElem.on('propertychange input', function(e) {
var value = maskedElem.cleanVal();
//changes mask
maskedElem.mask(value.length >= 8 ? masks[1] : masks[0]);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
Here's the solution i found using the mask properties
$(document).ready(function () {
$('#TelContato').unmask();
$('#TelContato').prop('placeholder', '9999-9999');
$('#TelContato').mask('0000-0000');
var SPMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 9 ? '00000-0000' : '0000-00009';
},
spOptions = {
onKeyPress: function (val, e, field, options) {
field.mask(SPMaskBehavior.apply({}, arguments), options);
}
};
$('#TelContato').mask(SPMaskBehavior, spOptions);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script>
<input asp-for="TelContato" class="form-control" maxlength="9" id="TelContato" />
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">
I am making a simple form and i have this code to clear the initial value:
Javascript:
function clearField(input) {
input.value = "";
};
html:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);"/>
But what i don't want is that if the user fills the input but clicks it again, it gets erased. I want the field to have the starter value "Name" only if the input is empty. Thank you in advance!
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
update
here is a demo fiddle of the same
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[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.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
Found here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
This may be what you want:
Working jsFiddle here
This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
var input= $(this);
input.innerHTML = '';
OP's question is no longer relevant- the question was asked in 2013 when the placeholder attribute wasn't well supported.
Nowadays you can just use <input placeholder="Your text here">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefplaceholder
I have an input field like this:
<input class="" type="text" id="Name_11_1" name="Name" value="Your name:">
And want to change it into this:
<input class="" type="text" id="Name_11_1" name="Name" value="Your name:" onblur="this.value = this.value || this.defaultValue;" onfocus="this.value == this.defaultValue && (this.value = '');"Your name:">
The problem is that I CAN'T edit the input field directly and have to use an external JavaScript code.
With jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function() {
$('#Name_11_1').blur(function() {
$(this).val(YOUR_EXPR);
});
$('#Name_11_1').focus(function() {
$(this).val(YOUR_EXPR);
});
});
</script>
First remove the existing event handlers and then attach your own:
var obj = document.getElementById('Name_11_1');
obj.removeAttribute('onfocus');
obj.removeAttribute('onblur');
obj.addEventListener('blur', function() {
// your js code for blur event
});
obj.addEventListener('focus', function() {
// your js code for focus event
});
If the browser understands the placeholder attribute on input tags, you can use that:
<input id="foo" name="foo" placeholder="Your name">
You can then add JavaScript to provide a fallback for other browsers:
if (!'placeholder' in document.createElement('input')) {
$('#foo').on('focus', function() {
// your code
}).on('blur', function() {
// your code
});
}
UPDATE: forgot that the OP can't edit the input tag directly. In that case, the code snippet can be modified to something like this:
var elem = $('#Name_11_1'),
defaultValue = 'Your name';
if ('placeholder' in document.createElement('input')) {
elem.attr('placeholder', defaultValue);
} else {
elem.on('focus', function() {
// your code
}).on('blur', function() {
// your code
});
}
I have an input text:
<input name="Email" type="text" id="Email" value="email#abc.example" />
I want to put a default value like "What's your programming question? be specific." in Stack Overflow, and when the user click on it the default value disapear.
For future reference, I have to include the HTML5 way to do this.
<input name="Email" type="text" id="Email" value="email#abc.example" placeholder="What's your programming question ? be specific." />
If you have a HTML5 doctype and a HTML5-compliant browser, this will work. However, many browsers do not currently support this, so at least Internet Explorer users will not be able to see your placeholder. However, see JQuery HTML5 placeholder fix « Kamikazemusic.com for a solution. Using that, you'll be very modern and standards-compliant, while also providing the functionality to most users.
Also, the provided link is a well-tested and well-developed solution, which should work out of the box.
Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a JavaScript fallback for browsers which don't support it yet.
If you are looking for a Mootools equivalent to the jQuery fallback in MvanGeest's reply, here is one.
--
You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.
Here's an example:
<input type="text" value="email#abc.example" name="Email" id="Email"
onblur="if (this.value == '') {this.value = 'email#abc.example';}"
onfocus="if (this.value == 'email#abc.example') {this.value = '';}" />
This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:
<script>
function onBlur(el) {
if (el.value == '') {
el.value = el.defaultValue;
}
}
function onFocus(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>
Using jQuery, you can do:
$("input:text").each(function ()
{
// store default value
var v = this.value;
$(this).blur(function ()
{
// if input is empty, reset value to default
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
// when input is focused, clear its contents
this.value = "";
});
});
And you could stuff all this into a custom plug-in, like so:
jQuery.fn.hideObtrusiveText = function ()
{
return this.each(function ()
{
var v = this.value;
$(this).blur(function ()
{
if (this.value.length == 0) this.value = v;
}).focus(function ()
{
this.value = "";
});
});
};
Here's how you would use the plug-in:
$("input:text").hideObtrusiveText();
Advantages to using this code is:
Its unobtrusive and doesn't pollute the DOM
Code re-use: it works on multiple fields
It figures out the default value of inputs by itself
Non-jQuery approach:
function hideObtrusiveText(id)
{
var e = document.getElementById(id);
var v = e.value;
e.onfocus = function ()
{
e.value = "";
};
e.onblur = function ()
{
if (e.value.length == 0) e.value = v;
};
}
Enter the following
inside the tag, just add onFocus="value=''" so that your final code looks like this:
<input type="email" id="Email" onFocus="value=''">
This makes use of the javascript onFocus() event holder.
Just use a placeholder tag in your input instead of value
we can do it without using js in the following way using the "placeholder" attribute of HTML5
( the default text disappears when the user starts to type in, but not on just clicking )
<input type="email" id="email" placeholder="xyz#abc.example">
see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder
<input name="Email" type="text" id="Email" placeholder="enter your question" />
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.
Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.
I think this will help.
Why remove value? its useful, but why not try CSS
input[submit] {
font-size: 0 !important;
}
Value is important to check & validate ur PHP
Here is a jQuery solution. I always let the default value reappear when a user clears the input field.
<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="email#abc.com" />
<script>
$("#Email").blur(
function (){
if ($(this).val() == "")
$(this).val($(this).prop("defaultValue"));
}
).focus(
function (){
if ($(this).val() == $(this).prop("defaultValue"))
$(this).val("");
}
);
</script>
I didn't see any really simple answers like this one, so maybe it will help someone out.
var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }
Here is an easy way.
#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.
$("#animal").on('click', function(){
var userVal = $("#animal-value").val(); // storing that value
console.log(userVal); // logging the stored value to the console
$("#animal-value").val('') // reseting it to empty
});
Here is very simple javascript. It works fine for me :
// JavaScript:
function sFocus (field) {
if(field.value == 'Enter your search') {
field.value = '';
}
field.className = "darkinput";
}
function sBlur (field) {
if (field.value == '') {
field.value = 'Enter your search';
field.className = "lightinput";
}
else {
field.className = "darkinput";
}
}
// HTML
<form>
<label class="screen-reader-text" for="s">Search for</label>
<input
type="text"
class="lightinput"
onfocus="sFocus(this)"
onblur="sBlur(this)"
value="Enter your search" name="s" id="s"
/>
</form>