Im using a simple form with a textarea, when the users clicks onto the textarea I want the contents of the textarea to be cleared.
Is this possible?
$('textarea#someTextarea').focus(function() {
$(this).val('');
});
If you only want to delete the default text (if it exists), try this:
$("textarea").focus(function() {
if( $(this).val() == "Default Text" ) {
$(this).val("");
}
});
By testing for the default text, you will not clear user entered text if they return to the textarea.
If you want to reinsert the default text after they leave (if they do not input any text), do this:
$("textarea").blur(function() {
if( $(this).val() == "" ) {
$(this).val("Default Text");
}
});
Of course, the above examples assume you begin with the following markup:
<textarea>Default Text</textarea>
If you want to use placeholder text semantically you can use the new HTML5 property:
<textarea placeholder="Default Text"></textarea>
Although this will only be supported in capable browsers. But it has the added advantage of not submitting the placeholder text on form submission.
My suggestion is that you only remove the initial default content on the first focus. On subsequent focuses, you risk removing user content. To achieve this, simply .unbind() the focus handler after the first click:
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
jsFiddle example
As a note, since you are using a textarea which has open and closing tags, you can can use $(this).text(""); or $(this).html("");... and, since the text inside a textarea is its value you can also use $(this).val(""); and $(this).attr("value", ""); or even this.value = "";.
HTML5 offers a more elegant solution to this problem: the "placeholder" attribute.
It'll create a text in background of your textarea which will appear only when the textarea is empty.
<textarea placeholder="Enter some text !"></textarea>
There are a couple of issues here that are only partially addressed in the current answers:
You need to clear the text when the user focuses the field
You only want to clear it the first time the user clicks on the field
You do not want the user to be able to submit the default text before it's been cleared
You might want to allow the user to submit the default text if they decide to type it back in. I have no idea why they'd want to do this, but if they insist on typing it back in, then I lean toward letting them do it.
With these details in mind, I'd add a class named "placeholder" to the field and use something like the following:
$("form textarea.placeholder").focus(function(e) {
$(this).text("");
$(this).removeClass("placeholder");
$(this).unbind(e);
});
Validate that the "placeholder" class name was removed when the form is submitted to guarantee that the user really, really wants to submit some stupid placeholder text.
If you're using the jQuery Validation Plugin, then you can put it all together like this:
$.validator.addMethod("isCustom", function(value, element) {
return !$(element).hasClass("placeholder");
});
$(form).validate({
rules: {
message: {
required: true,
isCustom: true
}
},
messages: {
message: "Message required, fool!"
},
submitHandler: function(form) {
$(form).find(":submit").attr("disabled", "disabled");
form.submit();
}
});
jQuery(function($){
$("textarea").focus(function(){
$(this).val("");
});
});
Something like this?
$('textarea#myTextarea').focus(function() {
if ($(this).val() == 'default text') {
$(this).val('');
}
});
<textarea type="text" onblur="if ($(this).attr('value') == '') {$(this).val('The Default Text');}" onfocus="if ($(this).attr('value') == 'The Default Text') {$(this).val('');}">The Default Text</textarea>
I found that simply
$('#myForm textarea').val('');
clears the form in Chrome but this did not work for Firefox (6.x). The value was empty in Firebug but the previous text still showed in the textarea. To get around this I select and rebuild the textareas one at a time:
$('#' + formId + ' textarea').each(function(i){
textareaVal = $(this).parent().html();
$(this).parent().html(textareaVal);
});
This finishes the job in Firefox and does not break Chrome. It will go through all of the textareas in a form one by one. Works in all other browsers (Opera, Safari, even IE).
This is possible and i think you are going for a code that can do this for more textareas than one...
This is what i use for my site:
Javascript:
<script type='text/javascript'>
function RemoveText(NameEle)
{
if ($('#' + NameEle) == 'default')
{
$('#' + NameEle).val('');
$('#' + NameEle).text('');
$('#' + NameEle).html('');
}
}
function AddText(NameEle)
{
if ($('#' + NameEle) == '')
{
$('#' + NameEle).val('default');
$('#' + NameEle).text('default');
$('#' + NameEle).html('default');
}
}
</script>
HTML:
<textarea cols='50' rows='3' onfocus='RemoveText(this)' onblur='AddText(this)' name='name' id='id'>default</textarea>
Related
I have some javascript which essentially removes a class which has a background image on focus, i.e clicking in the input box (which has the background image).
The code is as follows:
$(function(){
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
This works well, and removes .minbox when the user clicks within the input field, however what i want to do is if the user makes no changes to the input field, it should add the class back in as per at the beginning. At the moment, once the user clicks once, the class is gone for good, i would like it to come back if the user makes no changes to the input box, so for example clicks the input field but then clicks back out again without entering anything.
Any help? Possible?
I'm assuming you don't want the class .minBox to be added if the user has entered a value, but only if they decided not to enter anything, or chose to erase what they had entered.
To do this, you can use the blur event and check if there's anything entered:
$("#ets_gp_height").blur(function()=> {
if($(this).val().length < 1) $(this).addClass('minBox');
});
This will work for TABing out of the input and CLICKing out of it.
$(document).on("blur", "#ets_gp_height", function(){
if($(this).val() == '') {
$(this).addClass('minBox');
}
});
This code will add class 'minBox' when ever user goes out of input field without entering any value.
A working example, with and without jQuery:
Note: with onblur solution, method is called each time the field is blured, even when the value hasn't changed. with onchange solution, method is called only when the value has changed. That why onchange is a better solution.
WITHOUT JQUERY
function onChange(input){
input.value.length > 0 || setClassName(input, 'minbox') ;
}
function onFocus(input){
if(input.className == 'minbox')
{
input.className = '' ;
}
}
function setClassName(o, c){ o.className = c; }
input.minbox {background-color:red;}
<input type="text" id="ets_gp_height" class="minbox" onchange="onChange(this)" onfocus="onFocus(this)">
WITH JQUERY:
$(function(){
$("#ets_gp_height").change(function(){
$(this).val().length > 0 || $(this).addClass("minbox");
})
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
input.minbox {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ets_gp_height" class="minbox">
Now, If I hit the button, it clears all in the input field, and it automatically inputs "#marry" to it.
But, I don't want it to be cleared:(
What if I want to add "#marry" to the end of the strings that already exists in the input field?
How can I customize my javascript part?
Input field
<textarea class="box text_area" cols="10" id="input" name="comment[body]"></textarea>
button
<a href="#topic" id="username" value="#marry”><span class='btn'>reply</span></a>
javascript
$(document).on('click', 'a#username', function() {
$(".box#input").val($(this).attr('value'));
}
val() has a callback with the arguments index and value, you can use that to easily add something to the value.
$(".box#input").val(function(_, val) {
return this.value + 'some extra string';
});
$(document).on('click', 'a#username', function() {
var self = this;
$(".box#input").val(function(_, val) {
return val + self.value;
});
});
First of all adeneo's answer is good and you should read it. Here is an alternative solution that does not use jQuery:
I assume that both these elements are a part of a form. Let's say for instance the form has an ID of "post". We can access it using document.forms and then its fields as such:
var input = document.forms.post["comment[body]"];
Now, we can add to its value whenever the button is clicked. First select username with getElementById or querySelector and then add the event:
username.addEventListener("click", function(ev){
input.value += ev.target.value;
});
Or with jQuery (this also delegates if the element is not in the DOM yet):
$(document).on('click', 'a#username', function() {
input.value += this.value;
});
It might be desirable to append an extra space between the current text and the username.
append #marry at the end of text area. you can use bellow code its working fine.
$(document).on('click', 'a#username', function () {
var txtvalue = $(".box#input").val();
$(".box#input").val(txtvalue + $(this).attr('value'));
});
see jsfiddle link http://jsfiddle.net/F6mkh/1/
I have this auto-suggestion application for emails. it all works well, except when I click outside the input field and then click back in it clears what was there 'onFocus'. any Ideas how I can stop this from happening?
function suggest(inputString){
if(inputString.length == 0) {
$('#suggestions').fadeOut();
} else {
$('#email').addClass('load');
$.post("auto.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
$('#email').removeClass('load');
}
});
}
}
function fill(thisValue) {
$('#email').val(thisValue);
setTimeout("$('#suggestions').fadeOut();", 600);
}
<input type="text" id="email" onKeyUp="suggest(this.value);" onClick="fill();" />
The onClick="fill();" call on your element is executing fill(undefined) whenever you click on the input box.
The first thing this does is sets the value of the input box to thisValue (currently holding undefined) which would effectively erase your input box.
This has nothing to do with focus, try clicking the box, entering a value then clicking on the box again, it'll likely wipe the value too without clicking off first.
For what it's worth, you're probably over-complicating this. I imagine the requirement for the clearing of the box is to remove placeholder text. If you're designing for a remotely new browser use the HTML5 placeholder="E-Mail" to have the browser display that in a lighter text (or whatever) when the user hasn't entered anything.
If you have to support older browsers there's ways around this too, this is a simple but not perfect way (you can generalize this and make a jQuery plugin or go find one out there that exists already too):
HTML:
<input type="text" id="email" class="placeholder" value="E-Mail" />
CSS:
.placeholder { color: #ccc; }
Javascript:
;(function($) {
$(document).ready(function() {
$("#email").on('focus', function() {
var $this = $(this);
if ($this.hasClass('placeholder')) {
$this.removeClass('placeholder');
$this.val('');
}
});
$("#email").on('keyUp', function() {
// this is where your key-up code goes
});
});
})(jQuery);
I´m using the "placeholder" attr. for placeholder text in input-fields
I need to have this functionality in IE-incarnations too.
I want the Placeholder to hide on FOCUS! every workaround i found hides the placeholder when the first type is entered.
I´m unable to work it out myself, it needs to simply delete the input´s Placeholder-Text on focus but also recovers that placeholder-text on blur if input-value is empty.
I´m trying to put this to work
jQuery(document).ready(function () {
jQuery('[placeholder]').focus(function() {
input = jQuery(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
input.attr('placeholder','')
}
}).blur(function() {
var input = jQuery(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
jQuery(this).find('[placeholder]').each(function() {
var input = jQuery(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
});
this changes the value of the placeholder to "(nothing)" and the behaviour is as i want but on blur it cant recover the placeholder-value beacause its "(nothing)" now
//Update
the solution for me :
$(function()
{
$('input').each(function()
{
$(this).val($(this).attr('holder'));
});
$('input').focus(function()
{
if($(this).attr('holder')==$(this).val())
{
$(this).val('');
}
});
$('input').focusout(function()
{
if($.trim($(this).val())=='')
{
var holder = $(this).attr('holder');
$(this).val(holder);
}
});
});
If you don't want to use placeholder you can use the code below or use this simple jQuery plugin: jQuery Placeholder.
jsFiddle Live Demo Of Code Below
HTML
<input type='text' holder='First name'><br>
<input type='text' holder='Last name'><br>
<input type='text' holder='Age'>
JavaScript
$(function() {
$('input').each(function() {
$(this).val($(this).attr('holder'));
});
$('input').focus(function() {
if($(this).attr('holder')==$(this).val()) {
$(this).val('');
}
});
$('input').focusout(function() {
if($.trim($(this).val())=='') {
var holder = $(this).attr('holder');
$(this).val(holder);
}
});
});
Also you can use this simple jQuery plugin: jQuery Placeholder.
Use the placeholder attribute:
<input type="text" placeholder="Search here">
For browsers that do not support placeholder; you can use a polyfill
For Webkit based browsers and Firefox you can hide the placeholder in pure CSS:
input:focus::-webkit-input-placeholder,
input:focus::-moz-placeholder { opacity:0; }
Old and not the best way is:
<input type="text" name="fname" value="Enter text here" onFocus="if (this.value=='Enter text here'){this.value='';}"
onBlur="if (this.value==''){this.value='Enter text here';}" />
But it works even in IE6.
There are a number polyfills out there that will "add" placeholder functionality in browsers that do not support it. I've used jQuery Placeholder in the past, but there are quite a few others mentioned in the modernizr docs (scroll down to the section on placeholders).
The nice thing about jQuery Placeholder is that you shouldn't have to change/add any code aside from a reference to the library. Just add the placeholder attribute to your element.
here is my code to hide placeholder text on input and textarea focus(). Simple and working great.
$('textarea,input').focus(function(e){
val=$(this).attr('value');
if (!val)
$(this).attr('value',' ');
this.select();
}).blur(function(e){
val=$(this).attr('value');
if (val==' ')
$(this).attr('value','');
});
I use these 2 methods (jquery) to hide placeholder when the input gets focus, and when it loses focus and it is empty show placeholder.
input.focus
step-1: simply saving placeholder value into a universal variable( here pl)
step-2: set placeholder property of input to ''
input.focusout
step-1: set placeholder property of input to the saved variable(here pl)
var pl;
//on getting focus
$('input').focus(function(){
pl=$(this).prop('placeholder');
$(this).prop('placeholder','');
});
// on losing focus:
$('input').focusout(function(){
$(this).prop('placeholder',pl);
});
I have an email text box that contains the text '(Not Required)' until a user clicks on it, at which point it turns blank. I'm trying to make it to where if the user clicks another text box without entering an email address (or entering anything), the text box will revert to containing (Not Required).
Here's what I have:
$(document).ready(function () {
$('#email').val("(Not Required)");
// this part works fine
$('#email').click(function(){
if ($(this).val() == '(Not Required)'){
$(this).val('');
}
});
// this isn't working
$(':text').click(function(){
var em = $('#email').val().length();
if (em<3){
$('#email').val('(Not Required)');
}
});
});
I can't figure out why the second part isn't working correctly. Any help would be rewarded with a lifetime's devotion to yourself from myself in a very big way. Forever.
var em = $('#email').text().length();
Should be
var em = $('#email').val().length;
And I show you a better way do this by chain method:
$(document).ready(function () {
$('#email').val("(Not Required)").foucs(function() {
$(this).val('');
}).blur(function() {
if ($(this).val().length < 3 ){
$(this).val('(Not Required)');
}
});
});
You have to use $('#email').val().length instead of $('#email').text().length()
Change
$('#email').text().length();
to
$('#email').val().length;
And just a suggestion, why not use the blur() event of the email input to return the 'Not Required' text instead of waiting for a click on another input box?
click isn't the event you should catch. focus is the one to go. never forget keyboard navigation.
Don't query the DOM twice, save the DOM element and work with it.
use val() instead of text and length instead od length()
:text isn't a good selector. it implies the global selector $('*')
$(document).ready(function () {
var $email = $('#email');
$email.val("(Not Required)");
// this part works fine
$email.focus(function(){
if (this.value == '(Not Required)'){
this.value ='';
}
});
$('#otherTextBoxId').focus(function(){
if ($email.val().length <3 ){
$email.val('(Not Required)');
}
});
});