I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):
$("#txt1").select();
Is there a way to do the opposite? To deselect the content of a textbox? I have the focus event of a series of textboxes set to select the contents within them. There are times now that I want to focus a particular textbox WITHOUT selecting it. What I am planning on doing is calling the focus event for this particular textbox, but then follow it with a call to deselect it.
$("input[type=text]").focus(function() {
$(this).select();
});
//code....
$("#txt1").focus();
//some code here to deselect the contents of this textbox
Any ideas?
Thanks!
what about this:
$("input").focus(function(){
this.selectionStart = this.selectionEnd = -1;
});
If you just assign the value of the textbox to itself, it should deselect the text.
You need to set the selectionStart and selectionEnd attribute. But for some reason, setting these on focus event doesn't work (I have no idea why). To make it work, set the attributes after a small interval.
$(document).ready(function(){
$('#txt1').focus(function(){
setTimeout(function(){
// set selection start, end to 0
$('#txt1').attr('selectionStart',0);
$('#txt1').attr('selectionEnd',0);
},50); // call the function after 50ms
});
});
To "focus a particular textbox WITHOUT selecting it":
I would use the part of the patched jquery plugin jquery-fieldselection
using that you can call
$('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left
or use this reduced version that places the cursor at the end of the text (by default)
(function() {
var fieldSelection = {
setSelection: function() {
var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
var args = arguments[0] || {"start":len, "end":len};
/* mozilla / dom 3.0 */
if ('selectionStart' in e) {
if (args.start != undefined) {
e.selectionStart = args.start;
}
if (args.end != undefined) {
e.selectionEnd = args.end;
}
e.focus();
}
/* exploder */
else if (document.selection) {
e.focus();
var range = document.selection.createRange();
if (args.start != undefined) {
range.moveStart('character', args.start);
range.collapse();
}
if (args.end != undefined) {
range.moveEnd('character', args.end);
}
range.select();
}
return this;
}
};
jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();
used this way:
$('#my_text_input').setSelection(); // leaves the cursor at the right
Rather than selecting and then deselecting, why not just temporarily store a boolean on the dom element?
$("input[type=text]").focus(function() {
if($(this).skipFocus) return;
$(this).select();
});
//code....
$("#txt1").skipFocus = true;
$("#txt1").focus();
I'd like to suggest a simple solution
$("input[type=text]").focus(function() {
$(this).select();
});
$("input[type=text]").blur(function() {
$('input[type="hidden"][value=""]').select();
});
//code....
$("#txt1").focus();
Here is a simple solution without jquery
<input type="text" onblur="this.selectionStart = this.selectionEnd = -1;">
If you want to deselect a text box using jQuery do the following:
$(your_input_selector).attr('disabled', 'disabled');
$(your_input_selector).removeAttr('disabled');
Related
I have this code , which popups the highlighted text in the page . The problem I have is that the highlighted text always pops up at the end of the page ?
Does the create range return an integer value due to which I can make it popup at the middle of the line ? Is there any way that the pop up can be popped below the line under which the text is highlighted ?
The code so far is as follows
var getSelected = function() {
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else if(window.selection) {
t=window.selection.createRange();
}
return t;
}
$(document).ready(function(){
$(document).bind("mouseup",mouseup);
$(document).bind("mousedown",mousedown);
});
var mouseup=function(){
$('div#pop-up').show();
var st = getSelected();
document.getElementById("pop-up").innerHTML=st;
}
var mousedown = function(){
$('div#pop-up').hide();
}
The above is the JS file for it . While the html just has a div with an id of pop-up
The problem isn't within the selector . But the problem is where it popups . It popsup at the end of the page due to the innerHTML but I want it to popup near where the text is selected . How do I do that ?
The selection range is an object that describes what text you've highlighted, in which element, and its general state.
The reason there's an if there is because this is a semi-recent (been around for years, just not 100% compatible, so few use it) standard, and different vendors used different implementations.
If you're on a browser which supports getSelection, then get the object that function returns...
...else, if your browser has a window.selection object, which holds methods for reading the actual selection, then do that.
It's like the old days of doing event-listening.
Now, everything is .addEventListener.
Once upon a time, it was:
if (document.addEventListener) { el.addEventListener(evt, func, false); }
else {
func = function () { func.call(el, window.event); };
el.attachEvent(evt, func);
}
Or XMLHttpRequest versus window.ActiveXObject("msxml2.xmlhttp");s...
remove the else if condition it should be just else in your case:
var getSelected = function() {
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else {
t=window.selection.createRange();
}
return t;
}
Here is my javascript:
$(document).ready(function(){
$(".reply").click(function(){
var replyId = $(this).attr("id");
$("textarea[name='comment']").val("<reply:"+replyId+">");
$("textarea[name='comment']").ready(function(){
moveCursorToEnd($(this));
});
});
});
function moveCursorToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
I am somewhat new to functions with javascript however this does not seem to work It will put the value in but not focus to the textarea. I am sure I am doing something very dumb, any ideas?
The ready event for the textarea will not fire because once the event is attached the textarea has already been loaded. Also you must also pass the raw element, not the jQuery object into the function. Try to changing these lines
$("textarea[name='comment']").ready(function(){
moveCursorToEnd($(this));
});
to this
moveCursorToEnd($("textarea[name='comment']")[0]);
You are passing a jquery object to a function which is expecting a DOM element. You also want to get rid of the ready:
$(".reply").click(function(){
var replyId = $(this).attr("id");
var $textArea = $("textarea[name='comment']");
$textArea.val("<reply:"+replyId+">");
moveCursorToEnd($textArea[0]);
});
http://jsfiddle.net/wC5Qm/1/
how would this code be modified so it does not .focus() the first form object if it is readonly or disabled and to skip to the next form input for focus?
Currently it returns an error if the first input box is disabled, but i would also like to skip to the next input box if it's readonly too, and if all inputs are disabled and readonly, then it should not focus anything..
<script language="javascript" type="text/javascript">
// Focus first element
$.fn.focus_first = function() {
var elem = $('input:visible', this).get(0);
var select = $('select:visible', this).get(0);
if (select && elem) {
if (select.offsetTop < elem.offsetTop) {
elem = select;
}
}
var textarea = $('textarea:visible', this).get(0);
if (textarea && elem) {
if (textarea.offsetTop < elem.offsetTop) {
elem = textarea;
}
}
if (elem) {
elem.focus();
}
return this;
}
</script>
Actually using input:enabled:visible fixes alot of my issues, but i'm still trying to figure out if readonly, to skip to the next one.
use :
$(yourElement).not(":disabled").not(":readonly")
Well here is the answer anyways for those looking..
var elem = $('input:enabled:visible:not([readonly="readonly"])', this).get(0);
You need to change the condition to
if (elem && !elem.prop('readonly') && !elem.prop('disable')) {
I've pieced together some code to use in ASP.NET to prevent controls from losing focus on postback so a tab OR click of another control saves the users position and returns it.
In Page_Load I have the following:
PartNum_tb.Attributes["onfocus"] = "gotFocus(this)";
Department_tb.Attributes["onfocus"] = "gotFocus(this)";
PartWeight_tb.Attributes["onfocus"] = "gotFocus(this)";
Standard_rb.Attributes.Add("onfocus","gotFocus(this)");
Special_rb.Attributes.Add("onfocus","gotFocus(this)");
if (Page.IsPostBack)
Page.SetFocus(tabSelected.Value);
This is my Javascript (tabSelected is a hidden field):
<script type="text/javascript">
function gotFocus(control) {
document.getElementById('form1').tabSelected.value = control.id;
if (control.type == "text") {
if (control.createTextRange) {
//IE
var FieldRange = control.createTextRange();
FieldRange.moveStart('character', control.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
control.focus();
var length = control.value.length;
control.setSelectionRange(length, length);
}
}
}
</script>
The problem is when I tab or click onto one of the radio buttons, it returns focus to whatever the last control was instead which is unintuitive and confusing to a user. It does this because the RadioButton never gets focus, therefore the cursor position doesn't get updated. After extensive Google searching it appears that its not really possible to know when a RadioButton gains focus. Is there any solution known to even just work around this problem?
A solution may be adding a keypress event to the previous field and use the click event on the radios. Also, move the control.focus(); out of the if statement:
Javascript
function changeFocus(next) {
gotFocus(next);
}
function gotFocus(control) {
document.getElementById('form1').tabSelected.value = control.id;
control.focus();
if (control.type == "text") {
if (control.createTextRange) {
//IE
var FieldRange = control.createTextRange();
FieldRange.moveStart('character', control.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
var length = control.value.length;
control.setSelectionRange(length, length);
}
}
}
I am using jquery to keep the focus on a text box when you click on a specific div. It works well in Internet Explorer but not in Firefox. Any suggestions?
var clickedDiv = false;
$('input').blur(function() { if (clickedDiv) { $('input').focus(); } });
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Point to note: the focus() method on a jquery object does not actually focus it: it just cases the focus handler to be invoked! to actually focus the item, you should do this:
var clickedDiv = false;
$('input').blur( function() {
if(clickeddiv) {
$('input').each(function(){this[0].focus()});
}
}
$('div').mousedown(function() { clickedDiv = true; })
.mouseup(function() { clickedDiv = false });
Note that I've used the focus() method on native DOM objects, not jquery objects.
This is a direct (brute force) change to your exact code. However, if I understand what you are trying to do correctly, you are trying to focus an input box when a particular div is clicked when that input is in focus.
Here's my take on how you would do it:
var inFocus = false;
$('#myinput').focus(function() { inFocus = true; })
.blur(function() { inFocus = false; });
$('#mydiv').mousedown(function() {
if( inFocus )
setTimeout( function(){ $('#myinput')[0].focus(); }, 100 );
}
Point to note: I've given a timeout to focussing the input in question, so that the input can actually go out of focus in the mean time. Otherwise we would be giving it focus just before it is about to lose it. As for the decision of 100 ms, its really a fluke here.
Cheers,
jrh
EDIT in response to #Jim's comment
The first method probably did not work because it was the wrong approach to start with.
As for the second question, we should use .focus() on the native DOM object and not on the jQuery wrapper around it because the native .focus() method causes the object to actually grab focus, while the jquery method just calls the event handler associated with the focus event.
So while the jquery method calls the focus event handler, the native method actually grants focus, hence causing the handler to be invoked. It is just unfortunate nomenclature that the name of this method overlaps.
I resolved it by simply replace on blur event by document.onclick and check clicked element if not input or div
var $con = null; //the input object
var $inp = null; // the div object
function bodyClick(eleId){
if (eleId == null || ($inp!= null && $con != null && eleId != $inp.attr('id') &&
eleId != $con.attr('id'))){
$con.hide();
}
}
function hideCon() {
if(clickedDiv){
$con.hide();
}
}
function getEl(){
var ev = arguments[0] || window.event,
origEl = ev.target || ev.srcElement;
eleId = origEl.id;
bodyClick(eleId);
}
document.onclick = getEl;
hope u find it useful