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);
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">
I am trying to make a "composed component" which consists of an input field and a button.
I have the following jsfiddle as example:
http://jsfiddle.net/stt0waj0/
<div id="myComponent">
<input type="text" onBlur="this.style.border='1px solid red';">
<button type="button" onClick="alert('Hello World');">ClickMe</button>
</div>
The behavior I want is that when I leave the input field without writing any content, I get a validation error (red border in this case). This already works in the fiddle (content validation is not the scope of the question).
However, when I leave the input field by pressing the button, I will open a dialog which allows to select values for the input field, so in that case, I don't want the validation to run.
So, the concrete question about the fiddle: Can I click the input field, and then click the button and not have a red border? But, if I click the input field, and then click somewhere else, I want the red border (any onBlur except when button was clicked).
Is this possible without dirty tricks?
Things I want to avoid:
Set a timer on the first event to wait for the second (Reason: performance)
Make the onClick event always reset the red border on the text field (Reason: gui glitches)
Just to make it clear on what I'm looking for and why this question is interesting: the onBlur event is fired before the onClick event. However, I normally would need the onBlur to know that the onClick comes next, which is not possible. That's the point of the question.
Imagine a date picker which validates on empty field, when the field has focus and you press the calendar, you will get a validation error even though you're selecting a date. I want to know if there is an elegant way to handle such cases.
To make this work, you can postpone your validation function if user pressed the button.
Below is sample code and fiddle to show what i mean.
* Updated the fiddle to use select dropdown instead of a button *
Fiddle Demo
input.error {color: red; border: 1px solid red;}
<div id="myComponent">
<input id="btn" type="text" onBlur="inputBlur()">
<select type="button" data-btn="btn" onclick="inputButtonClick()" onchange="selectChange()" onblur="selectBlur()">
<option value="">choose</option>
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>
</div>
window.validate = function(input) {
//do your validation
var val;
console.log("Validating");
val = input.val();
if ( !val || !val.length) {
input.addClass("error");
console.log("Something is invalid");
} else {
//all good
console.log("All valid");
}
//clear error after x time to retry
setTimeout(function() {
$(".error").removeClass("error");
$("input").removeAttr("data-btn-active") ;
}, 3000);
}
window.selectBlur = function() {
var input = $("#" + $(event.target).attr("data-btn"));
validate(input);
}
window.selectChange = function() {
var input = $("#" + $(event.target).attr("data-btn"));
console.log("change", $(event.target).val() );
input.val( $(event.target).val() );
validate(input);
}
window.inputButtonClick = function() {
var input = $("#" + $(event.target).attr("data-btn"));
input.attr("data-btn-active", "true");
console.log("inputButtonClick",input );
}
window.inputBlur = function() {
var input = $(event.target);
//give a bit of time for user to click on the button
setTimeout(function() {
if (!input.attr("data-btn-active" ) ) {validate(input);}
}, 100);
}
$(document).ready(function() {
});
Given the following markup, I want to detect when an editor has lost focus:
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<div class="editor">
<input type="text"/>
<input type="text"/>
</div>
<button>GO</button>
EDIT: As the user tabs through the input elements and as each editor div loses focus (meaning they tabbed outside the div) add the loading class to the div that lost focus.
This bit of jquery is what I expected to work, but it does nothing:
$(".editor")
.blur(function(){
$(this).addClass("loading");
});
This seems to work, until you add the console log and realize it is triggering on every focusout of the inputs.
$('div.editor input').focus( function() {
$(this).parent()
.addClass("focused")
.focusout(function() {
console.log('focusout');
$(this).removeClass("focused")
.addClass("loading");
});
});
Here is a jsfiddle of my test case that I have been working on. I know I am missing something fundamental here. Can some one enlighten me?
EDIT: After some of the comments below, I have this almost working the way I want it. The problem now is detecting when focus changes to somewhere outside an editor div. Here is my current implementation:
function loadData() {
console.log('loading data for editor ' + $(this).attr('id'));
var $editor = $(this).removeClass('loaded')
.addClass('loading');
$.post('/echo/json/', {
delay: 2
})
.done(function () {
$editor.removeClass('loading')
.addClass('loaded');
});
}
$('div.editor input').on('focusin', function () {
console.log('focus changed');
$editor = $(this).closest('.editor');
console.log('current editor is ' + $editor.attr('id'));
if (!$editor.hasClass('focused')) {
console.log('switched editors');
$('.editor.focused')
.removeClass('focused')
.each(loadData);
$editor.addClass('focused');
}
})
A bit more complicated, and using classes for state. I have also added in the next bit of complexity which is to make an async call out when an editor loses focus. Here a my jsfiddle of my current work.
If you wish to treat entry and exit of the pairs of inputs as if they were combined into a single control, you need to see if the element gaining focus is in the same editor. You can do this be delaying the check by one cycle using a setTimeout of 0 (which waits until all current tasks have completed).
$('div.editor input').focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if ($.contains($editor[0], document.activeElement)) {
$editor.addClass("focused").removeClass("loading");
}
else
{
$editor.removeClass("focused").addClass("loading");
}
}, 1);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/8s8ayv52/18/
To complete the puzzle (get your initial green state) you will also need to also catch the focusin event and see if it is coming from the same editor or not (save the previous focused element in a global etc).
Side note: I recently had to write a jQuery plugin that did all this for groups of elements. It generates custom groupfocus and groupblur events to make the rest of the code easier to work with.
Update 1: http://jsfiddle.net/TrueBlueAussie/0y2dvxpf/4/
Based on your new example, you can catch the focusin repeatedly without damage, so tracking the previous focus is not necessary after all. Using my previous setTimeout example resolves the problem you have with clicking outside the divs.
$('div.editor input').focusin(function(){
var $editor = $(this).closest('.editor');
$editor.addClass("focused").removeClass("loading");
}).focusout(function () {
var $editor = $(this).closest('.editor');
// wait for the new element to be focused
setTimeout(function () {
// See if the new focused element is in the editor
if (!$.contains($editor[0], document.activeElement)) {
$editor.removeClass("focused").each(loadData);
}
}, 0);
});
Here's what worked for me:
$(".editor").on("focusout", function() {
var $this = $(this);
setTimeout(function() {
$this.toggleClass("loading", !($this.find(":focus").length));
}, 0);
});
Example:
http://jsfiddle.net/Meligy/Lxm6720k/
I think you can do this. this is an exemple I did. Check it out:
http://jsfiddle.net/igoralves1/j9soL21x/
$( "#divTest" ).focusout(function() {
alert("focusout");
});
I want to call a function when a certain field gets blurred, but only if a certain element is clicked. I tried
$('form').click(function() {
$('.field').blur(function() {
//stuff
});
});
and
$('.field').blur(function() {
$('form').click(function() {
//stuff
});
});
But neither works, I reckon it's because the events happen simultaneously?
HTML
<form>
<input class="field" type="textarea" />
<input class="field" type="textarea" />
</form>
<div class="click-me-class" id="click-me">Click Me</div>
<div class="click-me-class">Click Me Class</div>
jQuery
$('.field').blur(function() {
$('#click-me').click(function(e) {
foo = $(this).data('events').click;
if(foo.length <= 1) {
// Place code here
console.log("Hello");
}
$(this).unbind(e);
});
});
You can test it out here: http://jsfiddle.net/WfPEW/7/
In most browsers, you can use document.activeElement to achieve this:
$('.field').blur(function(){
if ($(document.activeElement).closest('form').length) {
// an element in your form now has focus
}
});
I have edited my answer because we have to take into account that the event is asigned every time.
It is not 100% satisfactory, and I don't recommend this kind of complicated way of doing things, but it is the more approximate.
You have to use a global variable to take into account the fact that the field was blurred. In the window event, it is automatically reset to 0, but if the click on "click-me" is produced, it is verified before the window event, becase window event is bubbled later, it happens inmediately after the "click-me" click event
Working code
$(window).click(function(e)
{
$("#result").html($("#result").html()+" isBlurred=0<br/>");
isBlurred=0;
});
var isBlurred=0;
$('.field').blur(function() {
$("#result").html($("#result").html()+" isBlurred=1<br/>");
isBlurred=1;
});
$('#click-me').click(function(e) {
if(isBlurred==1)
{
$("#result").html($("#result").html()+" clicked<br/>");
}
});
".field" would be the input and "#click-me" would be the element clicked only just once.
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>