Need help converting this inline javascript to a jQuery function - javascript

I have the following HTML/JS that shows an initial value, removes it when you click in the input field, and then re-populates it with the original value if you don't enter anything.
I need to do this on multiple input fields on the same page and thus would like to turn it into a jQuery function that I could then apply to any input field with a certain class.
<input type="text" name="search" value="Search by name" onfocus="if (this.value == 'Search by name') {this.value = '';this.style.color = '#000';}" onblur="if (this.value == '') {this.value = 'Search by name';this.style.color = '#aaa';}" />

Firstly, make your life easier and give the input a class:
<input type="text" class="search" name="search">
You can use an attribute selector:
$(":text[name='search']")...
but this is much faster:
$("input.search")...
and then use this:
$(function() {
$("input.search").focus(function() {
this.defaultval = this.defaultval || $(this).val();
if ($(this).val() == this.defaultval) {
$(this).val("").css("color", "#000");
}
}).blur(function() {
if ($(this).val() == "") {
$(this).val(this.defaultval).css("color", "#AAA");
}
});
});

$(":text[name='search']")
.focus(function(){
if ($(this).val() == 'Search by name')
$(this).val("").css("color", "black");
})
.blur(function(){
if ($(this).val() == "")
$(this).val("Search by name").css("color", "#aaa");
});

Turn it into a plugin
$.fn.inputMagic=function(text){
return this.each(function(){
var text=$(this).val()||text||''
$(this).focus(function(){
if ($(this).val() == text){
$(this).val("").css("color", "black");
}
}).blur(function(){
if ($(this).val() == ""){
$(this).val(text).css("color", "#aaa");
}
});
});
}
Then you can call it like this
$('input.search').inputMagic('Search by name').show();//and continue to chain

untested
jQuery(function () {
jQuery("input[type=text]").bind("focus",function(e){
var input = e.target;
input.defaultval = input.defaultval || input.value;
if(input.value==input.defaultval) {
input.value = "";
input.style.color = '#000';
}
}).bind("blur",function(e){
var input = e.target;
if(input.value == '') {
input.value = input.defaultval;
input.style.color = '#aaa';
}
})
});
edit: this seems to be a more general solution than the others. It takes as default text whatever happens to be in the input field first. Though I don't bother wrapping the event target in a jquery to alter the CSS.

Related

Clearing value on input not working when two classes present

Ok im using this code to clear the inputs, it works great!! as long as the input dont have two classes...
This is working
<input class="textBox" name="textBox" value="some value" >
$(document).ready(function() {
var default_val = '';
$('input[class^="textBox"]').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input[class^="textBox"]').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});
This is not working
But if the input changes to this
<input class="text_box textBox" name="textBox" value="some value" >
This is not working even if i change my code to
$(document).ready(function() {
var default_val = '';
$('input[class^="text_box textBox"]').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input[class^="text_box textBox"]').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});
This is the input where its not working
<input class="text_box textBox" type="text" name="email" id="email" value="Su Correo electrónico" size="22">
Use a class selector:
$(document).ready(function() {
var default_val = '';
$('input.textBox').focus(function() {
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input.textBox').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
});

How to escape ’ in this textarea so that onblur and onfocus will work?

My Codepen: http://codepen.io/leongaban/pen/jqEwF
The textarea below contains some javascript to clear the text when the user clicks and puts the default text back if the user does not type anything.
I need to escape the ’ so that the javascript will work
I've tried ' and just ' and when I click inside the textarea (onfocus) the text does not go away and I get this error in the console:
However when I try " it will work! But I need a ’ or a ' not "
<div id="the-accept-textarea">
<textarea id="accept-response-text" rows="5" cols="50"
value="I’d be happy to make this introduction if possible. Contact me at your convenience."
onblur="if (this.value == '') {
this.value = 'I’d be happy to make this introduction if possible. Contact me at your convenience.';}"
onfocus="if (this.value == 'I’d be happy to make this introduction if possible. Contact me at your convenience.')
{this.value = '';}">I’d be happy to make this introduction if possible. Contact me at your convenience.
</textarea>
</div>
How would you handle this?
UPDATE
trying this
var defaultValue = 'I\'d be happy to make this introduction if possible. Contact me at your convenience.'
var txtArea = document.getElementById("accept-response-text");
console.log('txtArea = '+txtArea);
console.log(defaultValue);
txtArea.value = defaultValue;
txtArea.focus = function() {
console.log('inside focus');
if (this.value === this.defaultValue) {
console.log('value is defaultValue');
this.value = '';
}
}
txtArea.blur = function() {
if (this.value === '') {
this.value = this.defaultValue;
}
}
However the focus and blur aren't working, but it is setting the value via Javascript to the textarea
<textarea id="accept-response-text" rows="5" cols="50" value=""></textarea>
All you need is
Live Demo
window.onload=function() {
var txtArea=document.getElementById("accept-response-text");
txtArea.onfocus=function() {
if (this.value === this.defaultValue) {
this.value = '';
}
}
txtArea.onblur=function() {
if (this.value === '') {
this.value = this.defaultValue;
}
}
}
UPDATE
Here is a version with placeholder and support for browsers without placeholders
Live Demo
function hasPlaceHolder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
window.onload=function() {
var txt_area_accept = document.getElementById("accept-response-text");
if (!hasPlaceHolder()) {
txt_area_accept.defaultValue=txt_area_accept.getAttribute("placeholder");
txt_area_accept.onfocus = function() {
if (this.value === this.defaultValue) {
this.value = '';
}
}
txt_area_accept.onblur = function() {
if (this.value === '') {
this.value = this.defaultValue;
}
}
}
}
You can escape them with \
if (this.value == '') {
this.value = 'I\'d be happy to make this introduction if possible. Contact me at your convenience.';
}
The code you posted in your update is correct, except that for adding events you assign to the on​focus and on​blur, not just focus and blur.
That said, you should really be using the placeholder attribute instead of what you're currently using.

JS: default text swap with live new element added

So for default text swapping on input (or other type of el) I have this snippet
<input class="js_text_swap" type="text" value="Enter your email" />
if($('.js_text_swap').length > 0) {
$('.js_text_swap').each(function() {
var that = $(this),
value = that.val(); // remembering the default value
that.focusin(function() {
if(that.val() === value) {
that.val('');
}
});
that.focusout(function() {
if(that.val() === '') {
that.val(value);
}
});
});
}
So my questions are:
1) does anybody has a better solution for this?
2) does anyone know how to make this work with live added elements (added with js after page has loaded)?
Thanks
Jap!
HTML
<input placeholder="Click..." class="text" type="text">
CSS
.text{color:#aaa}
.text.focus{color:#444}
JS
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
http://yckart.com/jquery-simple-placeholder/
UPDATE
To make it work with ajax or similar you need to convert it into a "plugin" and call it after your succesed ajax request (or after dynamically crap creating).
Something like this (very simple example):
jQuery.fn.placeholder = function() {
return this.each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
};
$("input:text, textarea").placeholder();
$("button").on("click", function() {
$(this).before('<input type="text" placeholder="default value" />');
$("input:text, textarea").placeholder();
});
demo

Input text form, using javascript to clear and restore form contents problem

I have this line of HTML
<input type="text" name="addQty" size="1"
class="addQty" value="0"
onclick="$(this).val('')"
onblur="itmQtyChk($(this).val())" />
the itmQtyChk function does this:
function itmQtyChk( qty ) {
if( qty == "") {
$(this).val("0");
} else {
$(this).val(qty);
}
}
My problem is I want it to return the original value to the input text if they exit the field and don't change anything, but it is not working.
Thank you for any help.
this in itmQtyChk function is not referring to the input but to the window object.
Change the function to accept the input as parameter:
function itmQtyChk(input) {
if (input.val() == "") {
input.val("0");
}
// the else part is not needed
}
with the onblur event also:
onblur="itmQtyChk($(this))"
Check this fiddle, it has lots of room for improvement, but it can help you:
http://jsfiddle.net/eDuKr/1/
$(function(){
var cacheQty;
$('.addQty').click(function(){
cacheQty = $(this).val();
$(this).val('');
}).blur(function(){
if ($(this).val() === ''){
$(this).val(cacheQty);
}else{
cacheQty = $(this).val();
}
});
});

How to save the value of INPUT in variable?

How to save the value of INPUT in variable to not to write a lot of duplicate code?
like var input = $(this).val();
full example
<div id="form">
1. <input type="text" value="title" />
2. <input type="text" value="value" />
</div>
$(function(){
$('#form input:eq(0)').bind({
focus: function(){
if($(this).val()=='title'){
$(this).val('');
}
},
blur: function(){
if($(this).val() == ''){
$(this).val('title');
}
}
});
$('#form input:eq(1)').bind({
focus: function(){
if($(this).val()=='value'){
$(this).val('');
}
},
blur: function(){
if($(this).val() == ''){
$(this).val('value');
}
}
});
});
I'm not exactly sure what you are asking, but this refactoring will work for toggling the value. EDIT: added default attribute to the html elements and shortened jQuery (still readable though) http://jsfiddle.net/UmZeZ/
<div id="form">
1. <input type="text" value="title" default="title" />
2. <input type="text" value="value" default="value" />
</div>
$(function() {
$('#form input').bind('focus blur', function() {
var value = $(this).attr('default');
if ($(this).attr('value') == value) {
$(this).attr('value', '');
} else if ($(this).attr('value') === '') {
$(this).attr('value', value);
}
});
});
To accomplish what you want, I would suggest using the HTML5 placeholder attribute. With Modernizr, we can detect browser support for this feature, and with this simple piece of code, we can get it to work even for browsers that do not support placeholder.
if(!Modernizr.input.placeholder){
var input = $('input[type="text"]');
input.focus(function(){
if(this.value === this.getAttribute('placeHolder')) this.value = '';
}).blur(function(){
if(this.value === '') this.value = this.getAttribute('placeHolder');
}).blur();
}
See a live demo of this here: http://www.jsfiddle.net/yijiang/cTDsL/1
Here is my solution. I would work to any field which has class="set-default"
Checkout the working example
Here is the code:
$(function(){
$('.set-default').bind({
focus: function(){
if(typeof($(this).data('def')) == 'undefined'){
$(this).data('def', this.value)
}
if(this.value == $(this).data('def')){
this.value = '';
}
},
blur: function(){
if(this.value == ''){
this.value = $(this).data('def');
}
}
})
});
basically all fields which had the class set-default will act as you like. You can always change the selector to $('#form input') but I think it's not useful.
HTH

Categories

Resources