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);
}
}
}
Related
I am currently trying to synchronize two checkboxes on a page.
I need the checkboxes to be synchronized - to this end, I'm using a Tampermonkey userscript to pick up when one of them is clicked. However, I'm at a loss as to how to do it.
I believe they are not actually checkboxes, but ExtJS buttons that resemble checkboxes. I can't check whether they're checked with JQuery because of this: the checked value is appended to a class once the JS behind the button has run.
I have tried preventDefault and stopPropagation, but either I'm using it wrong or not understanding its' usage.
I'm not quite clever enough to just call the JS behind the box instead of an onclick event. Otherwise, that would solve my issue.
This is my code:
//Variables - "inputEl" is the actual button.
var srcFFR = "checkbox-1097";
var destFFR = "checkbox-1134";
var srcFFRb = "checkbox-1097-inputEl";
var destFFRb = "checkbox-1134-inputEl";
//This checks if they're synchronised on page load and syncs them with no user intervention.
var srcChk = document.getElementById(srcFFR).classList.contains('x-form-cb-checked');
var destChk = document.getElementById(destFFR).classList.contains('x-form-cb-checked');
if (srcChk == true || destChk == false) {
document.getElementById(destFFRb).click();
} else if (destChk == true || srcChk == false) {
document.getElementById(srcFFRb).click();
}
//This is where it listens for the click and attempts to synchronize the buttons.
$(document.getElementById(srcFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(destFFRb).click();
}
});
$(document.getElementById(destFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(srcFFRb).click();
}
});
I'm at a bit of a loss...any help would be greatly appreciated.
Figured it out - I was comparing class lists without singling out what I wanted to actually match.
My solution:
$(document.getElementById(srcFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(destFFRb).click();;
}});
$(document.getElementById(destFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(srcFFRb).click();;
}});
On chrome, the "search" event is fired on search inputs when user clicks the clear button.
Is there a way to capture the same event in javascript on Internet Explorer 10?
The only solution I finally found:
// There are 2 events fired on input element when clicking on the clear button:
// mousedown and mouseup.
$("input").bind("mouseup", function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue == ""){
// Gotcha
$input.trigger("cleared");
}
}, 1);
});
The oninput event fires with this.value set to an empty string. This solved the problem for me, since I want to execute the same action whether they clear the search box with the X or by backspacing. This works in IE 10 only.
Use input instead. It works with the same behaviour under all the browsers.
$(some-input).on("input", function() {
// update panel
});
Why not
$("input").bind('input propertychange', function() {
if (this.value == ""){
$input.trigger("cleared");
}
});
I realize this question has been answered, but the accepted answer did not work in our situation. IE10 did not recognize/fire the $input.trigger("cleared"); statement.
Our final solution replaced that statement with a keydown event on the ENTER key (code 13). For posterity, this is what worked in our case:
$('input[type="text"]').bind("mouseup", function(event) {
var $input = $(this);
var oldValue = $input.val();
if (oldValue == "") {
return;
}
setTimeout(function() {
var newValue = $input.val();
if (newValue == "") {
var enterEvent = $.Event("keydown");
enterEvent.which = 13;
$input.trigger(enterEvent);
}
}, 1);
});
In addition, we wanted to apply this binding only to the "search" inputs, not every input on the page. Naturally, IE made this difficult as well... although we had coded <input type="search"...>, IE rendered them as type="text". That's why the jQuery selector references the type="text".
Cheers!
We can just listen to the input event. Please see the reference for details. This is how I fixed an issue with clear button in Sencha ExtJS on IE:
Ext.define('Override.Ext.form.field.ComboBox', {
override: 'Ext.form.field.ComboBox',
onRender: function () {
this.callParent();
var me = this;
this.inputEl.dom.addEventListener('input', function () {
// do things here
});
}
});
An out of the box solution is to just get rid of the X entirely with CSS:
::-ms-clear { display: none; } /* see https://stackoverflow.com/questions/14007655 */
This has the following benefits:
Much simpler solution - fits on one line
Applies to all inputs so you don't have to have a handler for each input
No risk of breaking javascript with bug in logic (less QA necessary)
Standardizes behavior across browsers - makes IE behave same as chrome in that chrome does not have the X
for my asp.net server control
<asp:TextBox ID="tbSearchName" runat="server" oninput="jsfun_tbSearchName_onchange();"></asp:TextBox>
js
function jsfun_tbSearchName_onchange() {
if (objTbNameSearch.value.trim() == '')
objBTSubmitSearch.setAttribute('disabled', true);
else
objBTSubmitSearch.removeAttribute('disabled');
return false;
}
ref
MSDN onchange event
- tested in IE10.
... or to hide with CSS :
input[type=text]::-ms-clear { display: none; }
The above code was not working in my case and I have changed one line and introduced $input.typeahead('val', ''); which works in my case..
// There are 2 events fired on input element when clicking on the clear button:// mousedown and mouseup.
$("input").on('mouseup', function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue === ''){
return;
}
// When this event is fired after clicking on the clear button // the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue === ''){
$input.typeahead('val', '');
e.preventDefault();
}
}, 1);
});
When double-clicking on a html page most browsers select the word you double-click on (or the paragraph you triple-click on). Is there a way to get rid of this behavior?
Note that I do not want to disable regular selection via single-click+dragging; i.e. jQuery UI's $('body').disableSelection() and the document.onselectstart DOM event are not what I want.
I fear you can't prevent the selection itself being "native behavior" of the browser, but you can clear the selection right after it's made:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
Edit: to also prevent selecting whole paragraph by "triple click", here is the required code:
var _tripleClickTimer = 0;
var _mouseDown = false;
document.onmousedown = function() {
_mouseDown = true;
};
document.onmouseup = function() {
_mouseDown = false;
};
document.ondblclick = function DoubleClick(evt) {
ClearSelection();
window.clearTimeout(_tripleClickTimer);
//handle triple click selecting whole paragraph
document.onclick = function() {
ClearSelection();
};
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
};
function RemoveDocumentClick() {
if (!_mouseDown) {
document.onclick = null;
return true;
}
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
return false;
}
function ClearSelection() {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
Live test case.
Should be cross browser, please report any browser where it's not working.
The following works for me in the current Chrome (v56), Firefox (v51) and MS Edge (v38) browsers.
var test = document.getElementById('test');
test.addEventListener('mousedown', function(e){
if (e.detail > 1){
e.preventDefault();
}
});
<p id="test">This is a test area</p>
The MouseEvent.detail property keeps track of the current click count which can be used to determine whether the event is a double, tripple, or more click.
Internet explorer unfortunately does not reset the counter after a timeout period so instead of getting a count of burst-clicks you get a count of how many times the user has clicked since the page was loaded.
Just put this on the css interested section
-moz-user-select : none;
-khtml-user-select : none;
-webkit-user-select : none;
-o-user-select : none;
user-select : none;
If you really want to disable selection on double-click and not just remove the selection afterwards (looks ugly to me), you need to return false in the second mousedown event (ondblclick won't work because the selection is made onmousedown).
**If somebody wants no selection at all, the best solution is to use CSS user-select : none; like Maurizio Battaghini proposed.
// set to true if you want to disable also the triple click event
// works in Chrome, always disabled in IE11
var disable_triple_click = true;
// set a global var to save the timestamp of the last mousedown
var down = new Date().getTime();
var old_down = down;
jQuery(document).ready(function($)
{
$('#demo').on('mousedown', function(e)
{
var time = new Date().getTime();
if((time - down) < 500 &&
(disable_triple_click || (down - old_down) > 500))
{
old_down = down;
down = time;
e.preventDefault(); // just in case
return false; // mandatory
}
old_down = down;
down = time;
});
});
Live demo here
Important notice: I set the sensitivity to 500ms but Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable. - api.jquery.com
Tested in Chrome and IE11.
Just to throw this out there, but here's the code I slap into my pages where I expect users to be clicking rapidly. However, this will also disable standard click-n-drag text selection.
document.body.onselectstart = function() {
return false;
}
document.body.style.MozUserSelect = "none";
if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
document.body.onmousedown = function() {
return false;
}
}
Seems to work well for me.
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
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');