Select all the text in an input, focusin - javascript

I want to have all the text selected when I give the focus to an element.
I used
$('.class-focusin').focusin(function(e) {
$(this).select();
});
But it's not the perfect behavior I want. When i click between two characters, the input value is not seleted, there is a cursor in the middle.
I want the behavior of the url bar in chrome browser: you click and the cursor is replaced by the value selection
Feel free to test my problem in this fiddle:
http://jsfiddle.net/XS6s2/8/
I want the text to be able to receive the cursor once selected.
The answer selected, below is definitely what I wanted, Thanks

You could have a variable to see if the text has been selected or not:
http://jsfiddle.net/jonigiuro/XS6s2/21/
var has_focus = false;
$('.class-focusin').click(function(e) {
if(!has_focus) {
$(this).select();
has_focus = true;
}
});
$('.class-focusin').blur(function(e) {
has_focus = false;
});

I guess you have to wait for the browser to give focus to the element, then do your selection:
$('.class-focusin').focus(function(e) {
var $elem = $(this);
setTimeout(function() {
$elem.select();
}, 1);
});
Yuck. Or simply bind to the click event instead:
$('.class-focusin').click(function(e) {
$(this).select();
});

Try using click instead of focusin.
$('.class-focusin').click(function(e) {
$(this).select();
});
Demo
Bye!

Working Demo http://jsfiddle.net/cse_tushar/XS6s2/22/
$(document).ready(function () {
$('.class-focusin').click(function (e) {
$(this).select();
});
});

It's a direct duplicate of Select all the text in an input, focusin, here's a nice answer from it
$(".class-focusin").on("focus",function(e){
$(this).select();
});
$(".class-focusin").on("mouseup",function(e){
e.preventDefault();
});
http://jsfiddle.net/XS6s2/31/

Related

Detect change in an input field when selecting value from a box

I want to detect a change in the input field when i select a value from the box like in the picture below.
html:
<input type="text" class="AgeChangeInput" id="range"/>
js:(not working)
<script>
$(document).ready(function()
{
alert("Hello");
$("#range").bind('input', function()
{
alert("done");
});
});
</script>
I also tried live on functions but they didn;t work too.
Your date selection box should fire a change event, then you only need to capture it:
$(function () {
$('#range').change(function () {
...
});
});
If the selection box doesn't fire the event, you'll need to trick the dom. Something like:
$(document).ready(function () {
// Asuming your selection box opens on input click
$('#range').click(function () {
$('.special-box-class').click(fireRangeEvent);
});
// Now the firing function
function fireRangeEvent() {
...
}
});
Hope it works
Try to use this code
changeDate - This event is fired when the date is changed.
$('#range').datepicker().on('changeDate', function(ev) {
//example of condition
if (ev.date.valueOf() > checkout.date.valueOf()) {
//make action here
alert('Here');
}
});

Prevent click after focus event

When user clicks on input field, two consecutive events are being executed: focus and click.
focus always gets executed first and shows the notice. But click which runs immediately after focus hides the notice. I only have this problem when input field is not focused and both events get executed consecutively.
I'm looking for the clean solution which can help me to implement such functionality (without any timeouts or weird hacks).
HTML:
<label for="example">Example input: </label>
<input type="text" id="example" name="example" />
<p id="notice" class="hide">This text could show when focus, hide when blur and toggle show/hide when click.</p>
JavaScript:
$('#example').on('focus', _onFocus)
.on('blur', _onBlur)
.on('click', _onClick);
function _onFocus(e) {
console.log('focus');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
$('#notice').removeClass('hide');
}
function _onClick(e) {
console.log('click');
$('#notice').toggleClass('hide');
}
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide');
}
UPDATED Fiddle is here:
I think you jumbled up the toggles. No need to prevent propagation and all that. Just check if the notice is already visible when click fires.
Demo: http://jsfiddle.net/3Bev4/13/
Code:
var $notice = $('#notice'); // cache the notice
function _onFocus(e) {
console.log('focus');
$notice.removeClass('hide'); // on focus show it
}
function _onClick(e) {
console.log('click');
if ($notice.is('hidden')) { // on click check if already visible
$notice.removeClass('hide'); // if not then show it
}
}
function _onBlur(e) {
console.log('blur');
$notice.addClass('hide'); // on blur hide it
}
Hope that helps.
Update: based on OP's clarification on click toggling:
Just cache the focus event in a state variable and then based on the state either show the notice or toggle the class.
Demo 2: http://jsfiddle.net/3Bev4/19/
Updated code:
var $notice = $('#notice'), isfocus = false;
function _onFocus(e) {
isFocus = true; // cache the state of focus
$notice.removeClass('hide');
}
function _onClick(e) {
if (isFocus) { // if focus was fired, show/hide based on visibility
if ($notice.is('hidden')) { $notice.removeClass('hide'); }
isFocus = false; // reset the cached state for future
} else {
$notice.toggleClass('hide'); // toggle if there is only click while focussed
}
}
Update 2: based on OP's observation on first click after tab focus:
On second thought, can you just bind the mousedown or mouseup instead of click? That will not fire the focus.
Demo 3: http://jsfiddle.net/3Bev4/24/
Updated code:
$('#example').on('focus', _onFocus)
.on('blur', _onBlur)
.on('mousedown', _onClick);
var $notice = $('#notice');
function _onFocus(e) { $notice.removeClass('hide'); }
function _onClick(e) { $notice.toggleClass('hide'); }
function _onBlur(e) { $notice.addClass('hide'); }
Does that work for you?
Setting a variable for "focus" seems to do the trick : http://jsfiddle.net/3Bev4/9/
Javascript:
$('#example').on('focus', _onFocus)
.on('click', _onClick)
.on('blur', _onBlur);
focus = false;
function _onFocus(e) {
console.log('focus');
$('#notice').removeClass('hide');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
focus = true;
}
function _onClick(e) {
console.log('click');
if (!focus) {
$('#notice').toggleClass('hide');
} else {
focus = false;
}
}
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide');
}
If you want to hide the notice onBlur, surely it needs to be:
function _onBlur(e) {
console.log('blur');
$('#notice').addClass('hide'); // Add the hidden class, not remove it
}
When doing this in the fiddle, it seemed to fix it.
The code you have written is correct, except that you have to replae $('#notice').removeClass('hide'); with $('#notice').addClass('hide');
Because onBlur you want to hide so add hide class, instead you are removing the "hide" calss.
I hope this is what the mistake you have done.
Correct if I am wrong, Because I don't know JQuery much, I just know JavaScript.
you can use many jQuery methods rather than add or move class:
Update: add a params to deal with the click function
http://jsfiddle.net/3Bev4/23/
var showNotice = false;
$('#example').focus(function(){
$('#notice').show();
showNotice = true;
}).click(function(){
if(showNotice){
$('#notice').show();
showNotice = false;
}else{
showNotice = true;
$('#notice').hide();
}
}).blur(function(){
$('#notice').hide();
});

How to Select / Highlight text box content on first click only

Please does anyone know the script that can help me highligh the content of a textfield on the first click
on the second click the selection / highligh should be cleared from the text box leavingg the insertion point.
Thank You in ADvance..
The script selects the text on the first click, but after every consecutive click the textarea will behave like a textarea always does. When the text area loses its focus due to the blur event and you click on it again, the text will be selected again.
Live Demo on JsFiddle
(function () {
var area = document.querySelector('#txt'),
clicked = false;
area.addEventListener('click', function () {
if (!clicked) {
area.select();
clicked = true;
}
});
area.addEventListener('blur', function () {
clicked = false;
});
})()
Because of addEventListener and querySelector the example is not fully cross browser compatible.
Try this: http://jsfiddle.net/4Hkhx/1/
$(document).ready(function(){
$('input').click(function(){
$(this).select();
});
});
function SelectText(sender) {
document.getElementById(sender.id).focus();
document.getElementById(sender.id).select();
}
<input type="text" id="tbTest" value="Test" onclick="SelectText(this)" />

jquery textarea value focus

This is probably stupidity on my part, but where am I going wrong with this?
$(function() {
$('textarea#comment').each(function() {
var $txt = $(this).val();
$(this).bind('focus', function() {
if($(this).val($txt)) {
$(this).val('');
}
});
});
});
Basically on focus I want to check if the value is the default value in this case 'Enter your comment', then if it is change the value to nothing.
Anyone know how to do this? I'm guessing its relatively simple. What the code does at the moment is removes any value.
Ok first off you should only have one tag with the id of comment since ids are supposed to be unique, but if we go with your code you have to setup a default value first like this:
<textarea id="comment">Enter text here</textarea>
Now the javascript:
(function() {
$('textarea#comment').each(function() {
var $txt = $(this).val();
//alert($txt);
$(this).bind('focus', function() {
if($(this).val() === this.defaultValue) {
$(this).val('');
}
});
});
})();
The self executing function syntax has been corrected here and should be as follow:
(function () { // my code here })();
and for default value use:
this.defaulValue; // works for input boxes as well
Hope it helps. Cheers
jquery_example plugin do exactly what you need. You may have a look at its source code and get some inspiration. Or you can store the default value as meta-data on the tag and check against it on change event of the textarea tag.
try
$('#comment').live('click change focus', function() {
var $txt = $(this).val();
if($txt == 'Enter your comment' );
$(this).val('');
});
DEMO

Detect which form input has focus using JavaScript or jQuery

How do you detect which form input has focus using JavaScript or jQuery?
From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.
I am not sure if this is the most efficient way, but you could try:
var selectedInput = null;
$(function() {
$('input, textarea, select').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
});
});
If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.
Otherwise, you could use the onfocus and onblur events.
something like:
<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />
and then have something like this in your javascript
if (txtfocus==1)
{
//Whatever code you want to run
}
if (txtfocus==0)
{
//Something else here
}
But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)
I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:
function getSender(field) {
switch (field.id) {
case "someID":
case "someOtherID":
return 1;
break;
default:
return 0;
}
}
function doSomething(elem) {
if (getSender(elem) == 1) {
// do your stuff
}
/* else {
// do something else
} */
}
HTML Markup:
<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />
The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).
-Tom
Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).
Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'true');
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'false');
}
}});
});
</script>
For pre-historic browsers, you can use the uglier:
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', Target.attr('name'));
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', null);
}
}});
});
</script>
You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:
var selectedInput = null;
$(function() {
$('form').on('focus', 'input, textarea, select', function() {
selectedInput = this;
}).on('blur', 'input, textarea, select', function() {
selectedInput = null;
});
});
(Maybe you should move the selectedInput variable to the form.)
You can use this
<input type="text" onfocus="myFunction()">
It triggers the function when the input is focused.
Try
window.getSelection().getRangeAt(0).startContainer

Categories