How to deslect highlighted text in textbox if already highlighted? - javascript

So I have this very simple JS function that selects all the text in the ASP.NET texbox (input):
function selectAllText(textbox) {
textbox.focus();
textbox.select();
}
..and it gets called like this on the click event:
$("#<%=Textbox1.ClientID %>").click(function () { selectAllText(jQuery(this)) });
The problem is no matter how many times a user clicks in the text box all of the text is always selected. I understand why this is occuring (based on the way my code above is), but it doesn't work well when the user tries to click in the middle of a word to get the cursor back to make a modification to the text.
How do I modify this JS to tell if the text is already highlighted and then deselect the text? This was on subsiquient click, the user can get the single cursor on a precise clicked location to make a modification.
I am trying to get the documentation on the .select() method to see if I could do if(!textbox.select()), but I am having a hard time finding it, so post any doc links as well if you have them.
EDIT: This problem and need for a workaround seems to be for IE (I am using IE9). In Chrome the behavior by default is what I need, but this is for an intranet application that runs on IE, so it appears I need an explicit workaround.
Thanks!

Is it necessary to do the .focus() in this function? You could instead attach a simple .select(); to the onfocus event (.bind('focus', function(){..})): http://jsfiddle.net/EGHzj/

Try this
$(document).ready(function(){
$('input').bind('click',function(){
if($(this).hasClass('selected')){
$(this).toggleClass('selected');
}else{
this.focus();
this.select();
$(this).toggleClass('selected');
}
});
});
This should work in IE also,
http://jsfiddle.net/rAqgw/7/

function selectAllText(textbox) {
// if there isn't selected text.
if (textbox[0].selectionEnd) {
textbox.focus();
textbox.select();
}
}
$('#txt').click(function() {
selectAllText($(this));
});
Live DEMO
​

Related

Disable auto focus on drop-down open of select2?

I tried to disable auto focus of input search inside select2 especially on mobile to disable keyboard popup. However, as documented here:
select2 will not be triggering the native events. select2 will also
not be triggering non-native versions of the events, which is less of
an issue as we still have the option to add the native events without
breaking compatibility.
So the only way I could do is to try to get every input box inside select2 that was currently on focused and set lose focus, but has no luck.
$("select").select2().on("select2-open",":input",function(){
setTimeout(function(){
$(":focus").blur();
}, 50);
});
Is there any possibility that I could achieve that result above? Thanks.
Finally, I managed to find solution which works just fine for me as below:
/* Hide keyboard on select2 open event */
function hideSelect2Keyboard(e){
$('.select2-search input, :focus,input').prop('focus',false).blur();
}
$("select").select2().on("select2-open", hideSelect2Keyboard);
$("select").select2().on("select2-close",function(){
setTimeout(hideSelect2Keyboard, 50);
});
Tested on Tablet, and iOS device. In function hideSelect2Keyboard(), I searched for every current focus element, include input field which could be used to initialized select2, setting .prop('focus',false) which will remove focus and consequently disable keyboard popup on select2-open and select2-close event, by chaining .blur() is to remove focus border from element. Then I attached this function to select event open and close and it works just fine.
I hope this will help other who searching for this as me too. Thanks.
I think I've found a solution for select v3 - tested in v3.5.4.
We can use the option shouldFocusInput, which must be a function that should return true or false.
So initialize the plugin with the following code:
$(document).ready(function() {
$('select').select2({
shouldFocusInput: function() {
return false;
}
});
});
Codepen demo: https://codepen.io/andreivictor/pen/JmNzvb
If you want to disable the auto-focus only on mobile devices, my approach is to use Modernizr library, which can test for the existence of Touch Events in the browser.
So the complete code should be:
$(document).ready(function() {
$('select').select2({
shouldFocusInput: function() {
if (Modernizr.touch) {
return false;
}
return true;
}
});
});
I am not sure why, but the above solutions didn't work for me. But this one worked-
$('select').on('select2:open', function (event) {
$('.select2-search input').prop('focus',false);
});

jQuery's .on blur function executes incorrectly in Firefox

The client wants a form in which entered numbers behave like Excel in certain ways. In particular, the data saved and the data displayed can be different, as it can in Excel. For example, the data saved could be 32425.537342 and the data displayed could be $32,425.54.
The approach we have taken to accomplish this is by using input pairs, one of type='text' and one of type='number'. The number input, which is by default hidden, stores the data to be sent and the text input displays it to the user. The number input is only displayed when the corresponding text input is focused, at which time such text input is hidden.
This following code behaves as expected in Chrome.
HTML:
<input type="text">
<input type="number">
<br>
<input type="text">
<input type="number">
jQuery:
$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
$(this).prev().show();
$(this).hide();
});
});
Fiddle. However, in Firefox (version 33.1.1) for Mac OS, the same is not working at all. When the text input is focused on, it disappears completely, without the number input ever being displayed.
In trying to ascertain where the problem is, I cut the code back to this:
$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
});
Fiddle. This actually works as expected in both Chrome and Firefox; on focus, the text input is permanently hidden and the number input is permanently displayed.
So it seems that the issue is in the second half of the code. If you take out the $(this).hide();, the code behaves consistently in Chrome and Firefox (although not in a way that's particularly useful):
$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
$(this).prev().show();
/* $(this).hide(); */
});
});
Fiddle. Likewise, if you remove only $(this).prev().show();, it also behaves the same in Chrome and Firefox: everything ultimately ends up hidden.
$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
/* $(this).prev().show(); */
$(this).hide();
});
});
Fiddle. The divergence in behavior only occurs when both lines are in there; Chrome hides one input and shows the other, whereas Firefox causes everything to disappear as soon as you focus on the text input.
I thought this might be related to the Firefox focus/blur issue that makes it behave strangely in iframes (example), but taking it out of JSFiddle's iframes didn't have any effect. Fiddle in full screen here.
So how do I make the behavior in Firefox match the behavior in Chrome?
This answer provided JavaScript that did the trick, and using that I was able to put together the equivalent in jQuery:
$(document).ready(function(){
$('[type="number"]').hide();
$('[type="text"]').on('focus',function(){
$(this).next().show().focus();
$(this).hide();
});
$('[type="number"]').on('blur',function(){
var $this = $(this);
setTimeout(function() {
if(!$(document.activeElement).is($this)){
$($this).hide();
$($this).prev().show();
}
}, 0);
});
});
Fiddle.
To quote from that answer as to why this is necessary:
[T]he issue is that different browsers choose to call event
handlers in different orders. One solution is to give the other events
a chance to fire by setting a timer for 0 milliseconds, and then
checking the fields to see which (if any) is focused.

Keeping an iPad keyboard up between inputs

Right now I'm using a bit of jQuery to hide the iPad keyboard when an input loses focus.
jQuery(function($) {
$(document).on('touchend', function(e) {
document.activeElement.blur();
});
});
However during a process like the checkout when a user clicks from input to input the keyboard disappears and the reappears every time the input is changed. Is there any way to change the above jquery code to where it only blurs the active element if the place on the document that is touched does NOT have an input type of text?
Well, I haven't tried this with iPad before, so I'm not sure that it will work, but you can check the type of document.activeElement to determine if it is a text or textarea field. If it isn't, then perform your blur(). The code would be like this:
jQuery(function($) {
$(document).on('touchend', function(e) {
setTimeout(function() {
var currentElement = document.activeElement;
if ($(currentElement).not("textarea, :text").length > 0) {
currentElement.blur();
}
}, 100);
});
});
The setTimeout is needed to make sure that the focus has transferred to the next element, before checking what the current element is (doing it immediately, will return the <body> as the activeElement).
This general approach (i.e., identifying what type the current activeElement is) works in a desktop browser environment, and it SHOULD work on an iPad, but, like I said earlier, I've not had a chance to test it there, so this is more of a "possible solution" than an actual "answer", until you give it a try and se if it works for you. :D

jQuery and textarea change events

i just met a strange behavior jQuery and can't figure out any more or less slight solution.
Say, i have textarea and button. I want to disable button if textarea is empty.
For this i have a handler which does this job.
Here is the code:
// textarea control
var $textarea = $('#myTextarea');
var $button = $('#myButton');
$textarea.on('input propertychange', function() {
if($textarea.val().length > 0) {
$button.removeClass('disabled').removeAttr('disabled');
} else {
$button.addClass('disabled').attr('disabled', 'disabled');
}
});
$button.on('click', function() {
if ($button.attr("disabled") != null) {
console.log('Disabled!');
return false;
} else {
// do some stuff and eventually erase textarea
$textarea.val('');
}
});
My trouble is when i erase textarea (the end of the code) it doesn't disable the button. Any ideas would be appreciated (actually it's slight adaptation of my code but the situation reflected pretty good, hope it would be clear for you, thanks!)
UPD
Nothing found on stackoverflow doesn't help.
UPD2
As i said in the begin, i was looking not for workaround like force trigger event, i thought it's possible to catch any event fired by $textarea.val(); Sure #Madbreaks and #epascarello 's solutions work pretty good, thanks guys.
Maybe just add this:
else {
// do some stuff and eventually erase textarea
$textarea.val('');
// notify
$textarea.trigger('propertychange');
}
problem is setting values with JavaScript does not normally trigger the events, but you can do it yourself.
$textarea.val('').trigger("input");
Make sure you trim the value of your textarea and you dont have an white spaces when you get the length of the .val(). Also in case you use a text editor like ckEditor make sure you read their documentation on how to retrieve the text being written.
Recommend using this jQueryTextChange lib. Its a cross browser consistent one. The usages are clearly elaborated on the home page. http://zurb.com/playground/jquery-text-change-custom-event

Trigger home button after input focus

I'm trying to bring the typing cursor to beginning of the input text by this code with no success. What is the issue?
HTML
<input value="text"/>
JavaScript(jQuery)
$('input').focus(function(){
$(this).delay(100).trigger(jQuery.Event("keydown",{keyCode: 36, which: 36}));
});
Live at JSBin
This looks like a case of over thinking a problem OR you did not describe it properly. The default behavior of focus is to place the cursor at the beginning of text. Just do this:
$(function() {
$('input').delay(100).trigger('focus');
});
Not sure why you need the delay. Using the jQuery ready event as shown you can elimintate the delay.
So, the problem is not really pressing home but moving cursor to beginning of the texbox I assune.
Checking this answer: move cursor to the beginning of the input field?
Generally the approach is right, but it doesn't seem to work directly
I have modified it to fit your jQuery on focus case:
$('input').focus(function(){
var input = this;
// for some reason, putting directly doesn't work
setTimeout(function() {
if (input.createTextRange) {
var part = input.createTextRange();
part.moveat("character", 0);
part.moveEnd("character", 0);
part.select();
}
else if (input.setSelectionRange){
input.setSelectionRange(0,0);
}
}, 0);
});
Live example:
http://jsfiddle.net/sF334/
If you want to trigger the focus itself, then you can do it as:
$('input').trigger('focus');
// use some unique selector instead in real example, like ID
Note it returns to before the first character on focus, but allows you to move and change selection later as you wish, as soon as you change focus and come back, it'll return to initial position again.

Categories