Change text color in text field - javascript

I have an input text field, which has a value "something" by default, but when I start to type, I want that the default value changes color, and the text i'll type, another one.
How can i do that?
<input type="text" value="something" onclick="this.value=''" />

To keep it simple like your example:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
And that should pretty much do it.

You may want to try the following:
<input type="text" value="something"
onFocus="if (this.value == 'something') this.style.color = '#ccc';"
onKeyDown="if (this.value == 'something') {
this.value = ''; this.style.color = '#000'; }">

Going off #chibu's answer, this is how you would do it using jQuery and unobtrusive Javascript
$(document).ready(
function() {
$("#mytext").bind(
"click",
function() {
$(this).val("");
$(this).css("color", "red");
}
);
}
)

// 'run' is an id for button and 'color' is for input tag
// code starts here
(function () {
const button = document.getElementById("run");
button.addEventListener("click", colorChange);
function colorChange() {
document.body.style.backgroundColor = document.getElementById("color").value;
}
})();

Here we go:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
Best of luck!
Keep coding!

Related

Onblur and Onfocus in input field that can't be edited

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
});
}

Password int on Textfield - NO jQuery/CSS3/HTML5

<input type="text" name="theName" value="password"
onblur="if(this.value == ''){ this.value = 'password'; this.style.color = '#333'; this.type="text";}"
onfocus="if(this.value == 'password'){ this.style.color = '#666';}"
onkeypress="if(this.value == 'password'){ this.value = ''; this.style.color = '#000';this.type="password";}"
style="color:#BBB;" />
Like this, if the textfield is onfocus but not a thing is been written on it, the DefaultValue will be visible with a lighter color. (more like the facebook search bar)...
But id doesn't work... What did i write wrong?
Another thing that i don't get is that if i take this javascript and i put it into a tag like this:
<script type="text/javascript">
function passfocus(){
if(this.value == 'password'){this.style.color = '#666';}}
function passblur(){
if(this.value == 'password'){ this.style.color = '#666';}}
function passkey(){
if(this.value == 'password'){
this.value = ''; this.style.color = '#000';this.type="password";}}
</script>
And i call this scripts in the textfield like this:
<input type="text" name="theName" value="password" onblur="passblur()"
onfocus="passfocus()" onkeypress="passkey()" style="color:#BBB;" />
Nothing works anymore... I think i kinda messed everything up!!
Why not simply use the placeholder HTML5 attribute?
<input type="text" placeholder="Default value"/>

Adding class to input when default value changed

I have an input field that has a default value added with JavaScript
<input type="text" class="input-text required-entry validate-value-eg" id="city_field" name="city" onfocus="if(this.value=='e.g. Bristol, Yorkshire') this.value='';" onblur="if(this.value=='') this.value='e.g. Bristol, Yorkshire';" value="e.g. Bristol, Yorkshire">
Whenever visitor click on this field the default value will dissipated and restore if not replaced by other value.
What I am trying to achieve is to add a class only if value has been changed from default?
Any help much appreciated,
Thanks
Dom
It is always a better practice to define your events in the script section or a separate .js file.
You don't need to handle that in a .change() event . You can check that in the .blur() event itself..
HTML
<input type="text" class="input-text required-entry validate-value-eg"
id="city_field" name="city" value="e.g. Bristol, Yorkshire">
Pure Javascript
var elem = document.getElementById('city_field');
elem.addEventListener('focus', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
this.value = '';
}
});
elem.addEventListener('blur', function() {
if (this.value == 'e.g. Bristol, Yorkshire') {
RemoveClass(this, "newClass")
}
else if (this.value == '') {
this.value = 'e.g. Bristol, Yorkshire';
RemoveClass(this, "newClass")
}
else {
this.className += " newClass";
}
});
function RemoveClass(elem, newClass) {
elem.className = elem.className.replace(/(?:^|\s)newClass(?!\S)/g, '')
}​
Javascript Fiddle
But you can achieve this with a loss lesser code by using other javascript frameworks.
This will make your life a lot easier but it is always good if you start out with javascript.
jQuery
$(function() {
var $elem = $('#city_field');
$elem.val('e.g.Bristol, Yorkshire'); // Default value
$elem.on('focus', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
this.value = '';
}
});
$elem.on('blur', function() { // Focus event
if (this.value == 'e.g.Bristol, Yorkshire') {
$(this).removeClass("newClass");
}
else if (this.value == '') {
this.value = 'e.g.Bristol, Yorkshire';
$(this).removeClass("newClass");
}
else {
$(this).addClass("newClass");
}
});
});​
jQuery Fiddle
Add an onchange handler to your input
<input type="text" class="input-text required-entry validate-value-eg"
id="city_field" name="city"
onchange="addClass(this)"
onfocus="if(this.value=='e.g. Bristol, Yorkshire') this.value='';"
onblur="if(this.value=='') this.value='e.g. Bristol, Yorkshire';"
value="e.g. Bristol, Yorkshire">
<script>
function addClass(input) // 'this' in onChange argument is the input element
{
if( input.value=='e.g. Bristol, Yorkshire')
{
$(input).removeClass("not_default_input_class");
$(input).addClass("default_input_class");
}
else
{
$(input).removeClass("default_input_class");
$(input).addClass("not_default_input_class");
}
}
</script>
EDIT: Added use of jQuery to add/remove the CSS classes
<script>
function addClass(input) // 'this' in onChange argument is the input element
{
input.className = input.value==input.defaultValue?
"default_input_class" : "not_default_input_class"
}
</script>

Easier way to toggle field descriptions using JavaScript

I've got a simple form that takes user feedback. Basically I just want to toggle the input values - Name, E-mail, Subject, Comments.
<form name="email_rep" id="email_rep" method="POST">
<input type="text" width="100" name="cust" value="Name" maxlength="100" class="fields" onFocus="toggleLabels(1)" onBlur="toggleLabels(5)">
<input type="text" width="100" name="cust_email" maxlength="100" value="E-mail" class="fields" onFocus="toggleLabels(2)" onBlur="toggleLabels(6)"><br />
<input type="text" width="100" name="cust_subject" value="Subject" maxlength="100" class="fields-alt" onFocus="toggleLabels(3)" onBlur="toggleLabels(7)"><br />
<input type="text" width="100" name="cust_comment" maxlength="500" value="Comments" class="fields-alt" onFocus="toggleLabels(4)" onBlur="toggleLabels(8)"><br />
<input type="submit" value="Send" name="submit_email" id="submit" onClick="sendButton()">
</form>
and the corresponding JS:
function toggleLabels(x) {
switch(x) {
case 1: (document.email_rep.cust.value=="Name") ? (document.email_rep.cust.value="") : (false); break;
case 2: (document.email_rep.cust_email.value=="E-mail") ? (document.email_rep.cust_email.value="") : (false); break;
case 3: (document.email_rep.cust_subject.value=="Subject") ? (document.email_rep.cust_subject.value="") : (false); break;
case 4: (document.email_rep.cust_comment.value=="Comments") ? (document.email_rep.cust_comment.value="") : (false); break;
case 5: (document.email_rep.cust.value=="") ? (document.email_rep.cust.value="Name") : (false); break;
case 6: (document.email_rep.cust_email.value=="") ? (document.email_rep.cust_email.value="E-mail") : (false); break;
case 7: (document.email_rep.cust_subject.value=="") ? (document.email_rep.cust_subject.value="Subject") : (false); break;
case 8: (document.email_rep.cust_comment.value=="") ? (document.email_rep.cust_comment.value="Comments") : (false); break;
}
}
I mean it works, but it's not exactly concise and definitely isn't reusable. I was thinking passing another variable - say "y" where y="email_rep", and possibly another - say "z" where z="Name"/"E-mail"/"Subject"/"Comments", but it's not working for me, I don't know if it's like the strings being passed or what the issue is. Any suggestions for making this simpler?
This seems to work. It uses placeholders, but also uses jQuery to simulate placeholder functionality: http://jsfiddle.net/kmkRV/
$(function() {
$("input:text").each(function() {
$(this).val($(this).attr("placeholder"));
}).focus(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
}).blur(function() {
if ($(this).val() == "") {
$(this).val($(this).attr("placeholder"));
}
});
});
That's the jQuery javascript. Here's the HTML:
<form name="email_rep" id="email_rep" method="POST">
<input type="text" width="100" name="cust" placeholder="Name" maxlength="100">
<input type="text" width="100" name="cust_email" maxlength="100" placeholder="E-mail"><br />
<input type="text" width="100" name="cust_subject" placeholder="Subject"><br />
<input type="text" width="100" name="cust_comment" maxlength="500" placeholder="Comments"><br />
<input type="submit" value="Send" name="submit_email" id="submit" onClick="sendButton()"> </form>
I think this is what you're trying to do:
function toggleLabelValue(obj, val) {
if (obj.value == val) {
obj.value = "";
} else {
obj.value = val;
}
}
// examples:
toggleLabelValue(document.email_rep.cust, "Name");
toggleLabelValue(document.email_rep.cust_email, "E-mail");
Or, since all your objects have the same root, you could build that root into the function like this:
function toggleRepLabelValue(field, val) {
if (document.email_rep[field].value == val) {
document.email_rep[field].value = "";
} else {
document.email_rep[field].value = val;
}
}
// examples:
toggleRepLabelValue("cust", "Name");
toggleRepLabelValue("cust_email", "E-mail");
Using jQuery, I've come up with possibly the most re-usable solution. Yes, it uses jQuery, however it's a very powerful, useful tool.
I've done some magic with .data() to store the original value. Take a look at this JSFiddle.
Code:
$(document).ready(function() {
$("input").each(function() {
$(this).data("placeholder", $(this).val());
});
$("input").live("focus", function() {
if($(this).val() == $(this).data("placeholder"))
{
$(this).val('');
}
});
$("input").live("blur", function() {
if(!$(this).val().length)
{
$(this).val($(this).data("placeholder"));
}
});
});
You could probably shrink it by a few lines, but I wanted it to be clear. Also, this will affect any new elements added dynamically to the DOM, due to using .live().
EDIT
To make for cleaner markup, have a look at THIS JSFiddle; it grabs the placeholder attribute and puts it into value as a fallback.
$(document).ready(function() {
$("input").each(function() {
$(this).data("placeholder", $(this).attr("placeholder"));
$(this).val($(this).data("placeholder"));
});
$("input").live("focus", function() {
if($(this).val() == $(this).data("placeholder"))
{
$(this).val('');
}
});
$("input").live("blur", function() {
if(!$(this).val().length)
{
$(this).val($(this).data("placeholder"));
}
});
} );
HTML5 has a lovely new attribute for input fields called placeholder.
Although this isn't supported by some browsers yet, I thought it worth pointing out as an answer for future readers.
You basically use it like:
<input type="text" placeholder="Your name">
http://jsfiddle.net/ZP9z3/
In Firefox, placing focus on the input removed the placeholder text, and on blur, if a new value isn't entered, the placeholder text is restored.
UPDATE
Using jQuery you can also mimick the behaviour of the placeholder with a small bit of code:
$('input:text').focus(function(){
$(this).val('');
}).blur(function(){
if($(this).val() == "")
{
$(this).val($(this).attr('placeholder'))
}
}
);
http://jsfiddle.net/ZP9z3/3/
This basically sets up each input so that it's placeholder text is used if it is empty.

Delete default value of an input text on click

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>

Categories