JQuery Empty A Textfield When I click in it - javascript

How do I empty a textfield (html form) if I click in it to write something.
Pseudo Code:
On click #searchform
Erase String in #searchform

$('#searchform').click(function() { $(this).val('') })

Try it here
$('#searchform').click(function() {
if ($(this).val() == 'Enter search term') {
$(this).data('original', $(this).val()).val('');
}
});
$('#searchform').blur(function() {
if ($(this).val() == '') {
$(this).val($(this).data('original'));
}
});
EDIT As of now you should use the placeholder attribute and if you want, use the above as a polyfill for missing placeholder support.
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
And turn the original code into a plugin for easy use (with some small mods).
jQuery.fn.placeholder = function() {
return this.each(function() {
var value = $(this).attr('placeholder');
jQuery(this).val(value).addClass('placeholder');
jQuery(this).focus(function() {
if (jQuery(this).val() == value) {
jQuery(this).val('').removeClass('placeholder');
}
});
jQuery(this).blur(function() {
if (jQuery(this).val() == '') {
jQuery(this).val(value).addClass('placeholder');
}
});
});
};

I'd recommend you using the HTML5 placeholder attribute. For example:
<input type="text" placeholder="some default string if empty" />
This will work with most of the newest browsers and for older ones there is a workaround jQuery plugin. Here is the link to the placeholder plugin.
And then you simply call:
$('input[placeholder]').placeholder();

If you are wanting to clear a default value from a field such as "Enter Search Term" I use the following code:
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
and then on my input field I add:
onfocus="clearText(this)"
So it would be:
<input type="text" name="username" value="enter your name here" onfocus="clearText(this)">

Related

Placeholder not working in IE10

html:
<div class="div-input">
<input type="text" id="loginname" name="username" value="" maxlength="25"
class="form-input" placeholder="Username"
/>
</div>
<div class="div-input">
<input type="password" id="loginpassword" name="password" maxlength="25"
class="form-input" placeholder="Password"
/>
</div>
<div>
<input type="submit" name="login" value="LOGIN" class="form-button"
onclick="return check_login("/")"
/>
<span id="logInfo"></span><span style="display: none;" id="overlay"></span>
<span style="display: none;" id="popup">
<img src="/public/images/loading.gif" />
</span>
</div>
My problem is that the placeholder is working fine in all browsers, for IE8 and IE9 I used Javascript to solve it, but in IE10 the placeholder is working, but not in a correct manner.
What happens is that on page load, if Placeholder is the placeholder, I get only Placeholde as placeholder in IE10 (last letter disappears), but if I click in the input box and outside the page it shows the correct placeholder as Placeholder.
If I type any word in the input field I am getting a cross symbol (close symbol) at the corner in the input field which is happening only in IE10.
It sounds like your javascript is breaking the native IE10 placeholder functionality.
To test this, and hopefully fix it, wrap the javascript you have written for placeholders in a conditional statement, so that it only applies to IE9 and below.
<!--[if lt IE 9]>
<script>
document.createElement('header');
document.createElement('nav');
</script>
<![endif]-->
Alternatively, there is a very nice jquery plugin by Mathias Bynens that is available for free and handles all of this for you: https://github.com/mathiasbynens/jquery-placeholder
Some CMSs already have a plugin built using this code. The Wordpress plugin is here: http://wordpress.org/plugins/html5-placeholder-polyfill/
i am not sure about placeHolder attribute for input support in ie10,but if u want a placeholder in ie u can do this throug jquery like this below..
if(navigator.appVersion.match(/MSIE [\d.]+/)){
var placeholderText = 'Some Placeholder Text';
$('#loginname').val(placeholderText);
$('#loginname').blur(function(){
$(this).val() == '' ? $(this).val(placeholderText) : false;
});
$('#loginname').focus(function(){
$(this).val() == placeholderText ? $(this).val('') : false;
});
}
u can do same for password too..
Have U tried somewhat like this using code...i believe should work...
$('#loginname').attr('placeholder', 'username');
$('#password').attr('placeholder', 'password');
Try this, is jquery pluin for placeholder in browser that don't support perfectly it. Leaving your php code and adding this js it should work:
(function($) {
/**
* Spoofs placeholders in browsers that don't support them (eg Firefox 3)
*
* Copyright 2011 Dan Bentley
* Licensed under the Apache License 2.0
*
* Author: Dan Bentley [github.com/danbentley]
*/
// Return if native support is available.
if ("placeholder" in document.createElement("input")) return;
$(document).ready(function(){
$(':input[placeholder]').not(':password').each(function() {
setupPlaceholder($(this));
});
$(':password[placeholder]').each(function() {
setupPasswords($(this));
});
$('form').submit(function(e) {
clearPlaceholdersBeforeSubmit($(this));
});
});
function setupPlaceholder(input) {
var placeholderText = input.attr('placeholder');
setPlaceholderOrFlagChanged(input, placeholderText);
input.focus(function(e) {
if (input.data('changed') === true) return;
if (input.val() === placeholderText) input.val('');
}).blur(function(e) {
if (input.val() === '') input.val(placeholderText);
}).change(function(e) {
input.data('changed', input.val() !== '');
});
}
function setPlaceholderOrFlagChanged(input, text) {
(input.val() === '') ? input.val(text) : input.data('changed', true);
}
function setupPasswords(input) {
var passwordPlaceholder = createPasswordPlaceholder(input);
input.after(passwordPlaceholder);
(input.val() === '') ? input.hide() : passwordPlaceholder.hide();
$(input).blur(function(e) {
if (input.val() !== '') return;
input.hide();
passwordPlaceholder.show();
});
$(passwordPlaceholder).focus(function(e) {
input.show().focus();
passwordPlaceholder.hide();
});
}
function createPasswordPlaceholder(input) {
return $('<input>').attr({
placeholder: input.attr('placeholder'),
value: input.attr('placeholder'),
id: input.attr('id'),
readonly: true
}).addClass(input.attr('class'));
}
function clearPlaceholdersBeforeSubmit(form) {
form.find(':input[placeholder]').each(function() {
if ($(this).data('changed') === true) return;
if ($(this).val() === $(this).attr('placeholder')) $(this).val('');
});
}
})(jQuery);
Then you have to invoke the plugin in your php page or in another js simply by:
$(function() {
// Invoke the plugin
$('input, textarea').placeholder();
});
Hope this helps!

autocomplete with JSP after select li suggesting the text input lose its selector

I use autocomplete box to suggest some value.
It works good with me but I have this problem after I select value the text input selector orange color is removed
My text input
<input type="text" size="30" value="" id="inputString"
onkeyup="lookup(this.value);" onblur="fill();" />
My JavaScript code
function lookup(inputString) {
if(inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("states.jsp", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
$('#suggestions li').click(function() {
var vel = $(this).html();
$('#inputString').val(vel);
});
}
});
}
}
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
#user1683781 How you are composing data in states.jsp page? You can add the css in same states.jsp page. Else you can add the css where you filling your data to input.
$('#inputString').css({"color":"orange","background-color":"#ccc"});
Let me know if this rectify your issue.

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

Using JQuery to get the default value of a textarea, clearing onfocus and reinstating value on empty

I have some JQuery that isn't working and I need a little help. I a few forms on my website, and they all have a textarea with the class ".form-textarea". What I'm trying to do is use JQuery to get the default value of the textarea, clear the value on focus and reinstate the original value if the the textarea is empty. I realise that an ID would probably be better but I need a generic function to affect all of the textareas with this particular class.
$(document).ready(function()
{
var def = $(".form-textarea")
$(".form-textarea").focus(function(srcc)
{
if ($(this).val() == def)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val(def);
}
});
$(".defaultText").blur();
});
This is an old method I used for the exact same purpose. I believe this is what you're looking for (uses Textareas) : Live demo
This uses the jQuery data API. I've also added an extra class so you can markup your text nicely (disabled_text). This is a general purpose method so all you need to do is add the suggest class to your textarea/input and the script will do the rest
<textarea class='suggest'>Some default value</textarea>
<textarea class='suggest'>Some default value2</textarea>
<textarea class='suggest'>Some default value3</textarea>
<input type='text' value ='me too' class='suggest'>
$('.suggest').each(function() {
$this = $(this);
if ($this.val() != '') {
return;
}
$this.data('defaultval', $this.val());
$this.addClass('disabled_text').focus(function() {
if ($this.val() == $this.data('defaultval')) {
$this.val('');
}
$this.removeClass('disabled_text');
}).blur(function() {
var oldVal = ($this.data('defaultval')) ? $this.data('defaultval') : '';
if ($this.val() == '' && oldVal != '') {
$this.addClass('disabled_text').val(oldVal);
}
})
});
Here, give this a whirl and see if it does the trick.
<script>
$(document).ready(function(){
$default = "defaultText";
$(".form-textarea").focus(function(){
if( $(this).val() == $default ){
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function(){
if( $(this).val() == "" ){
$(this).addClass("defaultTextActive");
$(this).val($default);
}
});
});
</script>
<input class="form-textarea" type="text" value="defaultText" />
<input class="form-textarea" type="text" value="defaultText" />
I've just tried to remove the value "srcc" from the focus function and it works fine

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